我看到 mvc 正在查找从 Html.DisplayFor 方法中的 lambda 函数传递给它的变量的名称:
@Html.HiddenFor(model => myModel.propA.propB)
可以生成类似于以下内容的 HTML:
<input id="myModel_propA_propB" type="hidden" value="" >
它显然使用了反射,但它超出了我的范围。有人可以帮我填写吗?
另外,是否可以创建一个 HTML 辅助函数,该函数采用完整的属性引用而不是 lambda 函数来完成类似的操作? IE。
@Html.HiddenFor(myModel.propA.propB)
...并且可以向助手传递完整的“myModel.propA.propB”引用,而不仅仅是 propB 的值? lambda 函数是完成此类任务的一种奇怪的 .net 解决方法,还是它实际上是所有编程学科的首选方法。
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.
发布评论
评论(1)
实际上,它正在遍历传递给辅助方法的表达式树以获取属性名称。在实践中,它看起来像:
当然这并不完整 - 例如,当传入的表达式中有多个属性调用时,您必须沿着表达式链向上走,您必须考虑其他表达式类型被传入的不是 MemberExpression 等等 - 但你明白了。请记住,表达式是表示为数据的代码表达式。另外,由于 MVC 是开源的,如果需要,您可以在源代码中查找它们用于获取 html 名称的确切代码。
对于第二个问题,答案是否定的。在没有 lambda 的情况下传递“仅属性”(这将是一个
Expression>
)是行不通的,因为这样函数只能看到传入的值 - 并且没有关于调用代码如何到达该值的信息。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:
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.