从ASP.NET MVC LAMBDA前pression获得价值 [英] Get value from ASP.NET MVC Lambda Expression

查看:128
本文介绍了从ASP.NET MVC LAMBDA前pression获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建自己的HTML辅助它发生在一个前pression(类似于内置LabelFor<>帮助我找到的例子来获得一个属性的值时,前pression与此类似:

I am trying to create my own HTML Helper which takes in an expression (similar to the built-in LabelFor<> helper. I have found examples to obtain the value of a property when the expression is similar to this:

model => model.Forename

不过,我的一些车型,我想获得子元素的属性,例如

However, in some of my models, I want to obtain properties in child elements, e.g.

model => mode.Person.Forename

在这些例子中,我不能反正找到(容易)获取录名字的价值。任何人都可以告诉我如何应该得到这个值。

In these examples, I cannot find anyway to (easily) obtain the value of Forename. Can anybody advise on how I should be getting this value.

感谢

推荐答案

如果您正在使用的LabelFor&LT相同的模式;>方法使用,那么前pression将永远是一个LambdaEx pression你可以直接执行它来获取值。

If you are using the same pattern that the LabelFor<> method uses, then the expression will always be a LambdaExpression and you can just execute it to get the value.

var result = ((LambdaExpression)expression).Compile().DynamicInvoke(model);

一般情况下,你总是可以在包装LambdaEx pressions通用前pressions然后编译和放大器;援引他们获得的价值。

Generally, you can always wrap generic expressions in LambdaExpressions and then compile & invoke them to get the value.

如果你想要的是没有用的名字的价值,但字段本身(FX,打印出字符串用的名字),那么你唯一的选择是使用某种形式的前pressionwalking的。在C#4的框架提供了一个名为防爆pressionVisitor可以使用这个类,但对于早期版本的框架,你必须自己实现它 - 请参见:<一href=\"http://msdn.microsoft.com/en-us/library/bb882521(VS.90).aspx\">http://msdn.microsoft.com/en-us/library/bb882521(VS.90).aspx

If what you want isn't the value of Forename, but the field itself (fx. to print out the string "Forename") then your only option is to use some form of expressionwalking. In C#4 the framework provides a class called ExpressionVisitor that can be used for this, but for earlier versions of the framework you have to implement it yourself - see: http://msdn.microsoft.com/en-us/library/bb882521(VS.90).aspx

这篇关于从ASP.NET MVC LAMBDA前pression获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆