Can Poyrazoğlu Can Poyrazoğlu - 2 months ago 16x
C# Question

How to get the value of a grandchild in an expression in C#?

I am building a helper method that takes a model expression and does something with its value, as in:


(that I can use as:
Html.EditorFor(m => m.Name)

I've implemented such method as:

public static MvcHtmlString MyMethod<TModel, TProperty>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> expression)
TModel dataModel = html.ViewData.Model;
MemberExpression mexp = expression.Body as MemberExpression;
PropertyInfo pinfo = mexp.Member as PropertyInfo;
string currentValue = dataModel != null ? pinfo.GetValue(dataModel) as string : null; //exception on this line
[do something with the value...]

This works for getting values of direct children of the model such as
, but for higher degree references, trying to get a value such as
is throwing an exception:

Object does not match target type.

After some investigation, it turns out that member expression is referencing
, where the property info holds info on
. When I try to get the value, it tries to get
in that sense, and crashes.

How do I get the value of grandchildren using expressions in C#?

usr usr

Name in model.SomeChild.Name is not a property of your model class. There is no such thing as a nested property. Name is a property get operation on the object returned by the SomeChild get operation. It's a bit like get_Name(get_SomeChild(model)) or model.get_SomeChild().get_Name() (pseudo-code).

In your code you would need to recursively unpack the MemberExpressions and build up a string from them.