Wednesday, November 02, 2011

MVC 2 Hidden Helper Extension

I don't know if you've ever needed to store an entire entity object inside a html page using the hidden form fields but for some reason the standard ASP.NET MVC HiddenFor() method doesn't do that. It only seems to work for simple data types such as ints and strings, etc.
So I wrote a little helper method to do just that.
It takes all the entity that you wish to store in your HTML page and iterates over each property and performs a Hidden() method call on them to ensure that all its properties are encoded as hidden fields so that it gets passed back to the Controller Action via the POST method.

public static MvcHtmlString HiddenEntirelyFor<TModel, TResult> (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression)
   ModelMetadata modelMetadata =
      ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
   List<string> htmlEntries =
         .Select(property => htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression) + "." + property.PropertyName, property.Model, null))
         .Select(mvcHtmlString => mvcHtmlString.ToHtmlString())
   return MvcHtmlString.Create(String.Join(Environment.NewLine, htmlEntries.ToArray()));

No comments: