Kirk Liemohn
Kirk Liemohn

Reputation: 7933

How can I use a lambda expression to get both the property "path" and the value?

I want to do something similar to what the HtmlHelpers do in ASP.NET MVC. Take the following:

@Html.EditorFor(model => model.SomeProperty.SomeInnerProperty)

The HtmlHelper can clearly get not only the value for SomeInnerProperty, but it also knows what I call the "path" to that property because it creates the appropriate HTML element with an attribute:

name="SomeProperty.SomeInnerProperty"

I want to do be able to create a method that can get both the value and the "path" similar to how the HtmlHelpers do. I did a little reflection into the existing HtmlHelpers and that looked like quite a rabbit hole. I have been able to create a method that consumes it like so:

MyCustomMethod(model => model.SomeProperty.SomeInnerProperty);

private void MyCustomMethod(Expression<Func<object, object>> expression)
{
    // I can inspect the expression object in the debugger here
}

When inspecting the "expression" object, I can figure things out through reflection, but I'm not sure how robust my solution would be because I am just figuring things out through observation. In addition, it just seems harder than it should be; like I am missing something simple.

Any ideas?

Upvotes: 5

Views: 985

Answers (2)

Alexandr Sulimov
Alexandr Sulimov

Reputation: 1924

//basic
MemberExpression memberExpression = (MemberExpression) expression.Body;
string name = (memberExpression.Expression as MemberExpression).Member.Name;
name += "." + memberExpression.Member.Name;

//cycle
MemberExpression memberExpression = (MemberExpression) expression.Body;
string name = "";
while (memberExpression.Expression is MemberExpression)
{
    name = memberExpression.Member.Name + "." + name;
    memberExpression = (MemberExpression)memberExpression.Expression;
}

Upvotes: 2

gp.
gp.

Reputation: 8225

To get the complete path:

expression.Body.ToString() will give you 'model.SomeProperty.SomeInnerProperty'. Get a substring after first dot to get 'SomeProperty.SomeInnerProperty'.

To get the value:

expression.Compile().Invoke(modelObject);

Upvotes: 2

Related Questions