Tuesday, October 23, 2012

ASP.NET MVC – Get field Name and Id for Model properties

ASP.NET MVC provides a number of convenient HtmlHelpers for form elements which accept a Lamda Expression returning a Model property as their first argument. The key advantages of these HtmlHelpers is that they simplify value binding and guarantee compile-time type-safety for selected Model members.

Html.TextBoxFor(m => m.Request.Name)
Html.LabelFor(m => m.Request.Name)

Sometimes it is necessary to know what the generated field Name or Id will be elsewhere in the view, but unfortunately, there is no public method available to return these values.

The following HtmlHelpers accept a Model property expression and return the same field Id and Name strings which would be produced by calling the standard form helpers.

public static string GetFullHtmlFieldName<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    return helper.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
}

public static string GetFullHtmlFieldId<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    return helper.ViewData.TemplateInfo.GetFullHtmlFieldId(expression);
}

public static string GetFullHtmlFieldName<TModel, TProperty>(this TemplateInfo templateInfo, Expression<Func<TModel, TProperty>> expression)
{
    return templateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
}

public static string GetFullHtmlFieldId<TModel, TProperty>(this TemplateInfo templateInfo, Expression<Func<TModel, TProperty>> expression)
{
    return templateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
}

4 comments:

N. Harebottle III said...

Awesome! Thanks for sharing!

jag said...

How do you use this in a view?

I've tried using it like you would use @Html.LabelFor(model => model.field), but this doesnt work and I get a no overload error. I'm guessing I'm missing a parameter?

Thanks

Nathan Taylor said...

Make sure to reference the namespace of the HtmlHelper either directly in the view or in your web.config. Check out this answer on stackoverflow: http://stackoverflow.com/a/3876409/143327.

Uwe Berthold said...

I'm currently refactoring a project which uses javascript to change the value of some input fields based on others.
When renaming properties in the ViewModel, it was easy to break the javascript without noticing.
With those extensions I can finally write lightweight "model-type-safe" javascript code

Thanks a lot!