2

Possible Duplicates:
Get method name and type using lambda expression
Can I use Expression<Func<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);
}
Community
  • 1
  • 1
nWorx
  • 2,145
  • 16
  • 37
  • I think it should stay open. @GvS's answer is really good and applicable to doing this sort of work in an asp.net mvc application. None of the other questions we've marked as dupes have his answer. – John Farrell Dec 29 '10 at 16:23
  • See also http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression -- there's a gotcha if you want nested properties (i.e. `Thing1.Thing2` from `o => o.Thing1.Thing2` -- see [my attempt for an alternative](http://stackoverflow.com/a/17220748/1037948) – drzaus Jun 20 '13 at 18:21

2 Answers2

2

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;
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
GvS
  • 52,015
  • 16
  • 101
  • 139
1

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.

driis
  • 161,458
  • 45
  • 265
  • 341
  • thanks for you fast response, but i get the error InvalidCastexception, cannot convert from "System.Linq.Expressions.UnaryExpression" to "System.Ling.Expressions.MemberExpression" – nWorx Dec 29 '10 at 13:27
  • thanks again,your hint with memberexpression has shown me the right way to solve this problem :-) i've updated my original post – nWorx Dec 29 '10 at 13:42