views:

58

answers:

2

Hi,

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

+2  A: 

Your looking for the value?

Why wouldn't this work?

    public object GetValue<T>( Expression<Func<T>> accessor )
    {
        var func = accessor.Compile();

        return func.Invoke();
    }
jfar
+3  A: 

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

AHM