Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Html Extension Helper with generic access to object property

Posted on: 2012-04-25

It's possible to create a custom generic Html Extension Helper with the use of Expression Helper and if required the ModelMetadata to get the value.

 public static string MyExtensionFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> property) { 
   var meta = ModelMetadata.FromLambdaExpression(property, this.HtmlHelper.ViewData); 
   string fullPropertyName = HtmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(property)); //Do what you need to do 
  } 

The variable fullPropertyNamemeta data contain the value of the property if required. @Html.MyExtensionFor(x=>x.MyClassProperty1)

With little or no code you can setup Html Helper that is strongly typed. This has the advantage to not write string. This of course is better to reduce the change to write a wrong string but also help the refactoring because all refactoring tools works with property name change.