Strongly Typed ASP.Net MVC Helpers

I've put together a short tutorial on creating ASP.Net MVC Helper Controls that use lambda expressions to strongly type the model, property and value parameters.

Although the ASP.Net MVC helpers are really useful, the one major drawback for me is having to use magic strings to set property values, especially when the properties might be deeply nested lists, or even deeply nests lists and properties within deeply nested lists.

To fix this situation I have wrapped the ASP.Net MVC helpers in order to set properties and values using lambda expressions.

Example calls:

  1. <% using (this.Html.BeginForm("Update", "Home"))
  2.    { %>     
  3.      <%= this.Html.RenderTextBoxFor(this.Model, c => c.FirstName)%>
  4.      <%= this.Html.RenderValidationMessageFor(this.Model, c=>c.FirstName ) %>
  5.      <%= this.Html.RenderTextBoxFor(this.Model, c => c.LastName)%>
  6.      <%= this.Html.RenderValidationMessageFor(this.Model, c=>c.LastName ) %>
  7. <%if (this.Model != null)
  8.   { %>
  9.      <% for (int i = 0; i < this.Model.Addresses.Count; i++)
  10.         { %>
  11.             House number <%= this.Html.RenderTextBoxFor(this.Model, c => c.Addresses[i].HouseNumber)%>    
  12.             <%= this.Html.RenderValidationMessageFor(this.Model, c => c.Addresses[i].HouseNumber)%>  
  13.                   
  14.             Postcode <%= this.Html.RenderTextBoxFor(this.Model, c => c.Addresses[i].Postcode)%>  
  15.             <%= this.Html.RenderValidationMessageFor(this.Model, c => c.Addresses[i].Postcode)%>                   
  16.    <%}%>   
  17.    <%} %>
  18.    <input type="submit" value="Submit" />
  19. <%} %>

As you can see, the above example is a basic user model with a first name, last name and a list of addresses, each textbox also has a corresponding validation message for displaying any model state errors (mainly just to show that as the controls are wrapping the ASP.Net MVC Helpers, you can still utilise model state as normal).

The rendered html source has the correct names required for use with model binding.

For example:

  1. <form action="/Home/Update" method="post">
  2.     <input id="FirstName" name="FirstName" type="text" value="Sean" />
  3.     <input id="LastName" name="LastName" type="text" value="McAlinden" />
  4.     
  5.             House number <input id="Addresses[0]_HouseNumber" name="Addresses[0].HouseNumber" type="text" value="12" />
  6.             Postcode <input id="Addresses[0]_Postcode" name="Addresses[0].Postcode" type="text" value="AB11 1CD" />  
  7.             
  8.             House number <input id="Addresses[1]_HouseNumber" name="Addresses[1].HouseNumber" type="text" value="34" />
  9.             Postcode <input id="Addresses[1]_Postcode" name="Addresses[1].Postcode" type="text" value="EF22 2GH" />
  10.    
  11.    <input type="submit" value="Submit" />
  12. </form>

In order to utilise this technique you need to create wrappers for each control you wish to use, below are examples of the two controls used above.

  1. using System;
  2. using System.Linq.Expressions;
  3. using System.Web.Mvc;
  4. using System.Web.Mvc.Html;
  5. namespace Demo.Helpers
  6. {
  7.     /// <summary>
  8.     /// Class with strong type wrappers for the mvc helper controls.
  9.     /// </summary>
  10.     public static class StronglyTypeControls
  11.     {
  12.         /// <summary>
  13.         /// Renders an mvc textbox control.
  14.         /// </summary>
  15.         /// <typeparam name="TModel">Accepts the type of model.</typeparam>
  16.         /// <typeparam name="TProperty">Accepts the type of property.</typeparam>
  17.         /// <param name="html">Extends the html object.</param>
  18.         /// <param name="model">Accepts the model.</param>
  19.         /// <param name="property">Accepts a lambda expression representing the property.</param>
  20.         /// <returns>Returns a string text box control.</returns>
  21.         public static string RenderTextBoxFor<TModel, TProperty>
  22.             (
  23.                 this HtmlHelper html,
  24.                 TModel model,
  25.                 Expression<Func<TModel, TProperty>> property
  26.             ) where TModel : class
  27.         {
  28.             return RenderTextBoxFor(html, model, property, null);
  29.         }
  30.         /// <summary>
  31.         /// Renders an mvc textbox control.
  32.         /// </summary>
  33.         /// <typeparam name="TModel">Accepts the type of model.</typeparam>
  34.         /// <typeparam name="TProperty">Accepts the type of property.</typeparam>
  35.         /// <param name="html">Extends the html object.</param>
  36.         /// <param name="model">Accepts the model.</param>
  37.         /// <param name="property">Accepts a lambda expression representing the property.</param>
  38.         /// <param name="htmlAttributes">Accepts an object containing html attributes.</param>
  39.         /// <returns>Returns a string text box control.</returns>
  40.         public static string RenderTextBoxFor<TModel, TProperty>
  41.             (
  42.                 this HtmlHelper html,
  43.                 TModel model,
  44.                 Expression<Func<TModel, TProperty>> property,
  45.                 object htmlAttributes
  46.             ) where TModel : class
  47.         {  
  48.             var propertyName = property.GetPropertyPath(model);
  49.             var propertyValue = property.GetValue(model);
  50.             var inputString = InputExtensions.TextBox(html, propertyName, propertyValue, htmlAttributes);
  51.             return inputString;
  52.         }
  53.         /// <summary>
  54.         /// Renders an mvc textbox control.
  55.         /// </summary>
  56.         /// <typeparam name="TModel">Accepts the type of model.</typeparam>
  57.         /// <typeparam name="TProperty">Accepts the type of property.</typeparam>
  58.         /// <param name="html">Extends the html object.</param>
  59.         /// <param name="model">Accepts the model.</param>
  60.         /// <param name="property">Accepts a lambda expression representing the property.</param>
  61.         /// <returns>Retuns a rendered validation control.</returns>
  62.         public static string RenderValidationMessageFor<TModel, TProperty>
  63.             (
  64.                 this HtmlHelper html,
  65.                 TModel model,
  66.                 Expression<Func<TModel, TProperty>> property
  67.             ) where TModel : class
  68.         {
  69.             var propertyName = property.GetPropertyPath(model);
  70.             var validationString = ValidationExtensions.ValidationMessage(html, propertyName);
  71.             return validationString;
  72.         }
  73.     }
  74. }

To finish this off, a helper class is required to generate the right property paths and values.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq.Expressions;
  5. using System.Reflection;
  6. using System.Text;
  7. namespace Demo.Helpers
  8. {
  9.     /// <summary>
  10.     /// Helper class to get property paths and values from a model.
  11.     /// </summary>
  12.     public static class StronglyTypedControlHelpers
  13.     {
  14.         /// <summary>
  15.         /// Gets the value of a model property.
  16.         /// </summary>
  17.         /// <typeparam name="TModel">Accepts the type of model.</typeparam>
  18.         /// <typeparam name="TProperty">Accepts the type of property.</typeparam>
  19.         /// <param name="propertyExpression">Accepts a lambda expression representing the property to get the value on.</param>
  20.         /// <param name="model">Accepts the model.</param>
  21.         /// <returns>A string property value.</returns>
  22.         public static string GetValue<TModel, TProperty>
  23.             (
  24.                 this Expression<Func<TModel, TProperty>> propertyExpression,
  25.                 TModel model
  26.             ) where TModel : class
  27.         {
  28.             if (model != default(TModel))
  29.             {
  30.                 return propertyExpression.Compile().Invoke(model).ToString();
  31.             }
  32.             return string.Empty;
  33.         }
  34.         /// <summary>
  35.         /// Gets the path of a property path including indexes on lists.
  36.         /// </summary>
  37.         /// <typeparam name="TModel">Accepts the type of model.</typeparam>
  38.         /// <typeparam name="TProperty">Accepts the type of property.</typeparam>
  39.         /// <param name="propertyExpression">Accepts a lambda expression representing the property to get the property path on.</param>
  40.         /// <param name="model">Accepts the model.</param>
  41.         /// <returns>A string property path.</returns>
  42.         public static string GetPropertyPath<TModel, TProperty>
  43.             (
  44.                 this Expression<Func<TModel, TProperty>> propertyExpression,
  45.                 TModel model
  46.             ) where TModel : class
  47.         {
  48.             List<string> pathItems = new List<string>();
  49.             BuildGraph(propertyExpression.Body, pathItems);
  50.             return BuildProperty(pathItems);
  51.         }
  52.         private static string BuildProperty(List<string> pathItems)
  53.         {
  54.             StringBuilder sb = new StringBuilder();
  55.             pathItems.Reverse();
  56.             foreach (var item in pathItems)
  57.             {
  58.                 if (sb.Length > 0)
  59.                 {
  60.                     sb.Append(".");
  61.                 }
  62.                 sb.Append(item);
  63.             }
  64.             return sb.ToString();
  65.         }
  66.         private static void BuildGraph(Expression expression, IList<string> pathItems)
  67.         {
  68.             if (expression is MemberExpression)
  69.             {
  70.                 BuildMemberExpressionProperty(expression, pathItems);
  71.             }
  72.             if (expression is MethodCallExpression)
  73.             {
  74.                 BuildMethodCallExpressionProperty(expression, pathItems);
  75.             }
  76.         }
  77.         private static void BuildMethodCallExpressionProperty(Expression expression, IList<string> pathItems)
  78.         {
  79.             AddMethodCallExpressionPropertyName(expression, pathItems);
  80.             if (MethodCallExpressionParent(expression) as ParameterExpression == null)
  81.             {
  82.                 BuildGraph(MethodCallExpressionParent(expression), pathItems);
  83.             }
  84.         }
  85.         private static Expression MethodCallExpressionParent(Expression expression)
  86.         {
  87.             return ((MemberExpression)(MemberExpression)((MethodCallExpression)expression).Object).Expression;
  88.         }
  89.         private static void BuildMemberExpressionProperty(Expression expression, IList<string> pathItems)
  90.         {
  91.             AddMemberExpressionPropertyName(expression, pathItems);
  92.             if (MemberExpressionParent(expression) as ParameterExpression == null)
  93.             {
  94.                 BuildGraph(MemberExpressionParent(expression), pathItems);
  95.             }
  96.         }
  97.         private static Expression MemberExpressionParent(Expression expression)
  98.         {
  99.             return ((MemberExpression)expression).Expression;
  100.         }
  101.         private static void AddMethodCallExpressionPropertyName(Expression expression, IList<string> pathItems)
  102.         {
  103.             pathItems.Add(MethodCallExpressionPropertyWithIndex(expression));
  104.         }
  105.         private static string MethodCallExpressionPropertyWithIndex(Expression expression)
  106.         {
  107.             return MethodCallExpressionProperty(expression) + GetIndex((MethodCallExpression)expression);
  108.         }
  109.         private static string MethodCallExpressionProperty(Expression expression)
  110.         {
  111.             return ((MemberExpression)((MethodCallExpression)expression).Object).Member.Name;
  112.         }
  113.         private static void AddMemberExpressionPropertyName(Expression expression, IList<string> pathItems)
  114.         {
  115.             pathItems.Add(((MemberExpression)expression).Member.Name);
  116.         }
  117.         private static string GetIndex(MethodCallExpression method)
  118.         {
  119.             MemberExpression args = (MemberExpression)method.Arguments[0];
  120.             object argValue = ((ConstantExpression)args.Expression).Value;
  121.             FieldInfo field = args.Member.DeclaringType.GetField(args.Member.Name);
  122.             int value = (int)field.GetValue(argValue);
  123.             return string.Format(CultureInfo.CurrentCulture, "[{0}]", value);
  124.         }
  125.     }
  126. }

The last point to add is this solution doesn't add the parameter prefix to the html so in your ActionResult methods you will need to set the prefix to an empty string for example:

public ActionResult Update([Bind(Prefix="")]Customer customer)

{

// Update Code

return View();

}

At this point you should have the two strongly typed helpers working nicely, even with complex domain graphs.

To finish them off, it would be worth having some Design By Contract checks on the methods to ensure valid parameters are passed in.

Although this is only a basic introduction to wrapping the controls, it is an especially useful technique when using the ASP.Net MVC controls on more complex models.

I hope this post is useful.

Kind Regards,

Sean McAlinden.

www.asp-net-mvc.com

2 Comments

  • Isn't this already implemented in ASP.NET MVC 2 Preview 2?

  • Hiya, I'm sure something similar is - for most places using mvc 1.0 at enterprise level, it's likely to be a while before they can upgrade.

    If anything, I just wanted to show a neat way of using expression trees to navigate the model as this technique can be used when creating custom helpers that won't form part of the mvc helper extensions.

Comments have been disabled for this content.