Click here to Skip to main content
15,892,298 members
Articles / Web Development / ASP.NET
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.93/5 (9 votes)
22 Jan 2014CPOL2 min read 23.5K   134   7  
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.

C#
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.

C#
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.

C#
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.

HTML
@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.

C#
   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.

C#
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.

HTML
@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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
He is awarded for Microsoft TechNet Guru, CodeProject MVP and C# Corner MVP. http://l-knowtech.com/

Comments and Discussions

 
-- There are no messages in this forum --