Get string property name from expression

前端 未结 4 693
暖寄归人
暖寄归人 2020-12-29 12:07

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:

4条回答
  •  醉梦人生
    2020-12-29 12:30

    public static class ExpressionsExtractor
    {
        public static string Lookup(this HtmlHelper html, Expression> 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);
    

提交回复
热议问题