Monday, July 02, 2012

MVC 3 Get the Html ID of a control for jQuery calls

jQuery makes the life of web developer simpler by addressing most of the browser compatibility issues. Every developer wants to make use of jQuery library to leave (most of) the browser related compatibilities to be taken care of by jQuery and concentrates on the actual requirements instead of worrying about other factors.

Integration of jQuery in any web project is as easier as it can be. The only important thing is to carefully pass the correct or appropriate id to jQuery calls. It is easier to view the generated source and hard code the corresponding ID to the jQuery calls. Ofcourse this would work and good for short term projects however for long term projects hard coding is not the best idea and nor is it recommended.

With traditional ASP.NET application, we use the following method to get hold of the Html ID that will  be generated for a control:

var id = $(“#<%=aspNetDotnetControl.ClientID %”>

This technique doesn’t work with ASP.NET MVC architecture. The following is one of the easiest way to do this in MVC 3:

1.       Define the extension method for the HtmlHelper class to return the fully qualified name for the given html (partial) field
2.       Define another extension method that just takes the fully qualified name and return the ID of the HTML element

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),
        System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static string NameFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            return htmlHelper != null ? htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)) : string.Empty;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),
        System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static string IdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            return HtmlHelper.GenerateIdFromName(NameFor(htmlHelper, expression));
        }

                After defining the above two extension methods, we are now ready to make use of it in our cshtml files as follows:

                $('#@Html.IdFor(m => m.Service.Name)')

       And that’s it.

No comments: