Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Create HTML Helpers Extension Method to Get Id and Name in jQuery Function

0.00/5 (No votes)
22 Jan 2014 1  
This tip introduces two extension methods of the HtmlHelper class, one that obtains the Id in a jQuery function and another obtains the Name in a jQuery function.

Introduction

This tip introduces two extension methods of the HtmlHelper class, one that obtains the Id in a jQuery function and another obtains the Name in a jQuery function. You create a strongly typed view then a field Id and Name are automatically created the same as a property name bound with the input field but we need the Id or Name of the input field in JavaScript to get the values. To get an Id or Name in a JavaScript function, we write a hardcoded string. This article provides a solution for that hard-coded string, in other words you can use an HTML Helper extension method in a JavaScript/jQuery function that takes the same model property as taken by the input filed. If you want to learn about extension methods then please go through the Extension Method In C# Tip/Tricks.

HTML Helper Extension Method to Get Id

Let's create a static class "HtmlExtension" that has an extension method for HTML Helper. After that, it creates a method in this class to get the Id of the input field in the JavaScript function using the model class property.

using System;
using System.Linq.Expressions;
using System.Web.Mvc;
namespace MvcHtmlHelperExample
{
    public static class HtmlExtension
    {
        public static string FieldIdFor<T, TResult>
        (this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
        {
            var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId
            (ExpressionHelper.GetExpressionText(expression));
            return id.Replace('[', '_').Replace(']', '_');
        }
    }
} 

After that, I create a model that binds with view.

namespace MvcHtmlHelperExample.Models
{
    public class Teacher
    {
        public string Name { get; set; }
    }
} 

Now create a controller that has an action method for the HTTP get request.

using System.Web.Mvc;
namespace MvcHtmlHelperExample.Controllers
{
    public class TeacherController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
} 

Thereafter, create a strong view that the input field binds with the model and create a JavaScript function that uses the HTML Helper extension method FieldIdFor() to get the Id of the input field and shows the input field's value in an alert message.

@model MvcHtmlHelperExample.Models.Teacher
@using MvcHtmlHelperExample
@{
    ViewBag.Title = "Index";
}
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">

    function GetName() 
    {
        var name = $("#@Html.FieldIdFor(model => model.Name)").val();
        alert(name)
    }
</script>

@using (Html.BeginForm())
{
    <fieldset>
        <legend>Teacher</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
        </div>
        <p>
            <input type="submit" value="Create" onclick="GetName()"/>
        </p>
    </fieldset>
} 

Run the application and get the value in an alert message of the name field.

Value by Id

Figure 1.1: Output Screen

HTML Helper Extension Method to Get Name

Now create another method in the "HtmlExtension" class to get the name of the input field in the JavaScript function using the model class property.

    public static string FieldNameFor<T, 
 TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
    {
        return html.ViewData.TemplateInfo.GetFullHtmlFieldName
        (ExpressionHelper.GetExpressionText(expression));
    } 

I am using previous Teacher model so there is no need to create a new model. Now create a controller action for HTTP Get Request type.

public ActionResult Teacher()
{
    return View();
}

Thereafter, create a strong view that the input field binds with the model and create a JavaScript function that uses the HTML Helper extension method FieldNameFor() to get the Name of the input field and shows the input field value in an alert message.

@model MvcHtmlHelperExample.Models.Teacher
@using MvcHtmlHelperExample
@{
    ViewBag.Title = "Teacher";
}
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">

    function GetName() 
    {
        var name = $("#@Html.FieldNameFor(model => model.Name)").val();
        alert(name)
    }
</script>

@using (Html.BeginForm())
{
    <fieldset>
        <legend>Teacher</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name):
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
        </div>
        <p>
            <input type="submit" value="Create" onclick="GetName()"/>
        </p>
    </fieldset>
} 

Run the application and we get the same result as in Figure 1.1. Download the zip folder for the entire source code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here