Possible Duplicates:
Get method name and type using lambda expression Can I use Expression<Fun开发者_C百科c<T, bool>> and reliably see which properties are referenced in the Func<T, bool>?
Hi,
I want to have a method, which I can use like this
<% Html.TextBoxFor(x=>x.Property, Helper.GetAttributes<ViewModel>(x=>x.PropertyA)) %>
The method header looks like this
public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)
but how do i find out the name of PropertyA? i need to do some checks before returning the right attributes. thanks in advance..
cheers
PS: thanks to driis post How to get names from expression property? i found the solution
it is
public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)
{
var item = myParam.Body as UnaryExpression;
var operand = item.Operand as MemberExpression;
Log.Debug(operand.Member.Name);
}
Create an instance of a ModelMetadata class:
var data = ModelMetadata.FromLambdaExpression<T, object>(myParam);
And now you can get all the information you need, with respect to attributes used on your model:
var propName = data.PropertyName;
var label = data.DisplayName;
That could be:
string propertyName = ((MemberExpression) myParam.Body).Member.Name;
In production code, you should probably check the Expression type before the cast and throw an appropiate exception if the expression passed in is not MemberExpression.
精彩评论