Omu Omu - 1 year ago 82
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 Source
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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download