How does the mvc HtmlHelper DisplayFor function extract the full property path from a lambda function?

I see that mvc finds the names of the variables passed to it from the lambda function in the Html.DisplayFor method:

@Html.HiddenFor(model => myModel.propA.propB) 

can generate HTML code like:

 <input id="myModel_propA_propB" type="hidden" value="" > 

obviously uses reflection, but it's outside of me. can someone fill me up?

ALSO, is it possible to create an HTML helper function that, instead of referencing a lambda function, can use a property reference to do something similar? i.e.

 @Html.HiddenFor(myModel.propA.propB) 

... and the assistant can be given the full link "myModel.propA.propB", and not just the value of propB? is an odd .NET lambda function a workaround for this kind of task, or is it really the preferred approach in all programming disciplines.

+4
source share
1 answer

In fact, this is an expression tree move that you pass to the helper method to get the property names. In practice, it looks something like this:

 MemberExpression memberExpression = (MemberExpression) expression.Body; propertyName = memberExpression.Member.Name; 

Of course, this is not complete - for example, you will need to approach the expression chain when there are several property calls in the passed expression, you will have to consider other types of expressions that are passed than MemberExpression, etc., but you get this idea . Remember that an expression is a code expression that is represented as data. Also, since MVC is open source, you can find the exact code that they use to get the html name in the sources if you want.

To answer the second question, the answer is no. Passing β€œonly properties” without a lambda (which will be Expression<Func<T,object>> ) will not work, because then the function can only see the passed value - and nothing about how the call code arrived with this value.

+6
source

All Articles