Home » ASP » ASP.MVC » Html Extension Helper with generic access to object property

Html Extension Helper with generic access to object property

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.