Click here to Skip to main content
Click here to Skip to main content

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

, 22 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sandeep Singh Shekhawat
Software Developer
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 22 Jan 2014
Article Copyright 2014 by Sandeep Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid