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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With