RJP Software Blog

.Net info and code snippets

Strongly Typed Helpers in ASP.Net MVC

without comments

This is something that I discovered on a project quite some time ago. I recently needed to do the same thing on my current project and after digging a round a bit remembered how it is done.

As I am sure you know it is fairly easy to write extension methods for the HtmlHelper in MVC (both Razor and Webform views). For example, if I was going to write an extension method for the JQuery DatePicker I would do something like:

public static string DatePicker(this HtmlHelper helper, string name, object date)
{
    var html = new StringBuilder();
    html.AppendFormat(@"<input id="{0}" class="datepicker"
                       type="text" name="{1}" value="{3}" />", id, name, date);
    return html.ToString();
}

This is ok but like most people I hate having to resort to using magic strings…

Fortunately the MVC framework comes to the rescue. If you download the source code and take a look at how strongly typed helper functions are managed internally, you will find that there are a couple of static methods that are publicly available: ModelMetadata.FromLambdaExpression and ExpressionHelper.GetExpressionText.

Using these classes we can rewrite the Helper method as follows:

public static string DatePickerFor(this HtmlHelperhelper,
                        Expression<Func<TModel, TProperty>> expression)
{
    var dateVal = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
    var name = ExpressionHelper.GetExpressionText(expression);

    html.AppendFormat(@"<input id="{0}" class="datepicker" type="text"
                        name="{1}" value="{3}" />", id, name, dateVal );
    return html.ToString();
}

Written by Rich

December 5th, 2011 at 4:03 pm

Posted in Asp.Net