Html Extension Helper with generic access to object property
Posted on: April 25, 2012
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.
1public static string MyExtensionFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> property) {2 var meta = ModelMetadata.FromLambdaExpression(property, this.HtmlHelper.ViewData);3 string fullPropertyName = HtmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(property)); //Do what you need to do4 }
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.