Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Kirk Liemohn Avatar asked Oct 01 '22 09:10

Kirk Liemohn


1 Answers

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);

like image 122
gp. Avatar answered Oct 10 '22 12:10

gp.