Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value of a property o => o.Property1 , defined in lambda

I need to get the value of a property defined in a lambda

 public static MvcHtmlString MyHelper<T, TProperty>(
            this HtmlHelper<T> html,
            Expression<Func<T, TProperty>> prop)
        {
            var value = \\ get the value of Prop1 (not the name "Prop1")
          ...
        }

the intended usage is something like:

public class FooViewModel 
{
    public string Prop1 { get;set; }
}

<%@ Page ViewPage<FooViewModel> %>

<%=Html.MyHelper(o => o.Prop1) %>
like image 754
Omu Avatar asked Jan 10 '11 08:01

Omu


1 Answers

Why do you need expression here? If you only want to have property value, Func<T, TProperty> is sufficient - it is like any other delegate, just invoke it:

public static MvcHtmlString MyHelper<T, TProperty>(
    this HtmlHelper<T> html,
    Func<T, TProperty> prop)
{
    var obj = // ??
    var value = prop(obj); \\ get the value of Prop1 (not the name "Prop1")
    ...
}

Where obj is the object from which you want to read the value (I can't see the object around your code).

like image 115
NOtherDev Avatar answered Oct 30 '22 18:10

NOtherDev