Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from ASP.NET MVC Lambda Expression

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.

Thanks

like image 744
user460667 Avatar asked Sep 28 '10 13:09

user460667


1 Answers

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);

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

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

like image 166
AHM Avatar answered Oct 12 '22 03:10

AHM