Omu Omu - 11 days ago 5
C# Question

Get string property name from expression

I'm trying to write a strongly typed helper
which would be something like this:

Html.Lookup(x => x.FooId);


for now I have this:

public static MvcHtmlString Lookup<T,TReturn>(this HtmlHelper<T> html, Func<T, TReturn> expression)
{
// get string "FooId" here
}


anybody knows how to get this ?

Answer
public static class ExpressionsExtractor
{
    public static string Lookup<T, TProp>(this HtmlHelper<T> html, Expression<Func<T, TProp>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;

        if (memberExpression == null)
            return null;

        return memberExpression.Member.Name;
    }
}

You would then call it with:

var propName = Html.Lookup(x => x.FooId);
Comments