MVC 2 Strongly Typed Helper Method

Some quick information about generating a strongly types helper method in MVC 2: Covers:

  • An Expression as a method argument
  • Getting a valid name for the form field
  • Getting type information about the property specified on the view.

An Expression as a method argument

The Below gives a basic example of a strongly types helper method definition

public static MvcHtmlString MyHelperFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression)

{
}

Getting a valid name for the form field

Say we put this into the view

<%= Html.EnumDropDownFor(Model => Model.ContactDetails.Phone.Type) %>

We can generate a form field name like this:

var fullPropertyPath =
    htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(
        ExpressionHelper.GetExpressionText(expression)); 

This would result in fullPropertyPath being “ContactDetails.Phone.Type”. We can then use this as the name attribute on the form field we render.

Getting type information about the property specified on the view.

We can also get meta data about the type that the …Phone.Type property get’s/sets using ModelMetadata class’s FromLambdaExpression method like this:

var modelMetadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(
    expression, htmlHelper.ViewData);

var propertyType = modelMetadata.ModelType;
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: