how does mvc HtmlHelper DisplayFor function extract the full property path from the lambda function?
I see that mvc is finding the names of the variables passed to it from the lambda function in an Html.DisplayFor method:
@Html.HiddenFor(model => myModel.propA.propB)
could generate HTML something like:
<input id="myModel_propA_propB" type="hidden" value="" >
it is obviously using reflection, but it is beyond me. could someone fill me in?
ALSO, is it 开发者_开发技巧possible to create an HTML helper function that takes a fully property reference instead of a lambda function to accomplish something similar? ie.
@Html.HiddenFor(myModel.propA.propB)
...and the helper could be passed the full "myModel.propA.propB" reference and not just the value of propB? is a lambda function an odd .net workaround to accomplish this sort of task or is it actually the preferred approach across all programming disciplines.
Actually, it is traversing the Expression tree you pass into helper method in order to get the property names. In practice, it would look something like:
MemberExpression memberExpression = (MemberExpression) expression.Body;
propertyName = memberExpression.Member.Name;
Of course that is not complete - for instance, you would have to walk up the chain of Expressions when there are multiple property invocations in the expression passed in, you would have to account for other expression types being passed in than MemberExpression, etc., etc. - but you get the idea. Remember that an Expression is a code expression represented as data. Also, since MVC is open source, you could look up the exact code they use to arrive at the html name in the sources, if you want.
To address your second question, the answer is no. Passing "just the property" without the lambda (which will be an Expression<Func<T,object>>
), will not work, because then the function can only see the value passed in - and nothing about how the calling code arrived at that value.
精彩评论