lundi 22 août 2016

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

I am building a helper method that would take a model expression and do something with its value, just as in:

Html.EditorFor(expression)

(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 model.Name, but for higher degree references, trying to get value such as model.SomeChild.Name is throwing an exception:

Object does not match target type.

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

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





Aucun commentaire:

Enregistrer un commentaire