How do the MVC html helpers use expressions to get an objects property
Asked Answered
T

2

19

For example:

Html.TextBoxFor(x => x.ModelProperty)

If I were to get an expression like this as a method argument, how would I get the referenced property from the expression? My experience with expressions is somewhat limited and based on what I know, I don't get how this works.

Tirol answered 16/1, 2014 at 20:42 Comment(0)
B
14

You can get property name easily like this:

var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var propName = metadata.PropertyName;

Or you can get property and its attributes:

MemberExpression memberExpression = (MemberExpression) expression.Body;
var member = memberExpression.Member as PropertyInfo;
var attributes = member.GetCustomAttributes();

For example you can write a simple method that generates a input element like this:

public static MvcHtmlString TextboxForCustom<TModel, TResult>(this HtmlHelper<TModel> html,
        Expression<Func<TModel, TResult>> expression)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        var propName = metadata.PropertyName;

        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("<input type=\"text\" id=\"{0}\" />", propName);

        return MvcHtmlString.Create(sb.ToString());

    }

Take a look at my answer here.

Blase answered 16/1, 2014 at 20:51 Comment(0)
S
9

I once wrote my own EditorFor, it had the following definition:

public static MvcHtmlString MyHtmlEditorFor<TModel, TProperty>(this HtmlHelper<TModel> h, Expression<Func<TModel, TProperty>> expression)
{
  // ...
}

To get the information of the property I used the ModelMetadata class:

ModelMetadata m = ModelMetadata.FromLambdaExpression(expression, h.ViewData);
var value = m.Model;
Sinh answered 16/1, 2014 at 20:47 Comment(4)
Out of curiosity, why did you say var value, but call out the type of m explicitly rather than just var m, especially when the type of m is obvious?Dorathydorca
because Model could be any object... he could of been vary specific or used object also.Sacchariferous
@RobertHarvey I added that line as an example in my answer, in reality I did some checks on the type before casting it to an explicit type.Sinh
I used MVC html helpers as an example of where I have seen this used.Tirol

© 2022 - 2024 — McMap. All rights reserved.