Client Id for Property (ASP.Net MVC)

Put this code somewhere:

using System; 
using System.Linq.Expressions; 
using System.Web.Mvc; 

namespace MvcLibrary.Extensions 
{ 
    public static class HtmlExtensions 
    { 
        public static MvcHtmlString FieldIdFor<TModel, TValue>(this HtmlHelper<TModel> html,
            Expression<Func<TModel, TValue>> expression) 
        { 
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
            string inputFieldId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName); 
            return MvcHtmlString.Create(inputFieldId); 
        } 
    } 
}

Then in your ASPX view:

<label for="<%= Html.FieldIdFor(m => m.EmailAddress) %>">E-mail address:</label> 
<%= Html.TextBoxFor(m => m.EmailAddress) %>

You can also use this in JavaScript calls as you won’t know the control’s ID in advance and may need it for some JavaScript code to work against it:

<script> $.CoolJQueryFunction('<%= Html.FieldIdFor(m => m.EmailAddress) %>'); </script>

The LabelFor HTML helper method, that someone mentioned here, won’t let you specify the actual text label you want to use, you have to decorate your ViewModels with attributes to set the label text, with IMHO is ugly. I’d rather that stuff appear in the actual ASPX view part itself, not on some domain/view model. Some people will disagree with me though.

Not sure of the rules for posting links to one’s blog posts, but I posted a blog on this exact topic: http://www.dominicpettifer.co.uk/Blog/37/strongly-typed–label–elements-in-asp-net-mvc-2

Leave a Comment