C#表达式更改主体(属性为SubProperty)

时间:2014-10-25 22:37:49

标签: c# expression

我创建了自定义助手,需要更改表达式主体。

模型

public class Customer
{
    public string Name { get; set; }
}

public class Report
{
    public Customer Customer { get; set; }
}

使用帮助

@Html.TextBoxForAdv(report => report.Customer)
public static MvcHtmlString TextBoxForAdv<TModel, TProperty>(
    this HtmlHelper<TModel> helper,
    Expression<Func<TModel, TProperty>> value)
{
   //value = { report.Customer };
   //At this place i want change Customer to Customer.Name
   string property = SomeFunction(typeof(Report)) return "Name";
   //value = { report.Customer.Name (from property) };

   return helper.TextBoxFor(helper, value);
}

我得到财产

Expression expr = Expression.Property(expression, "Name");

但新表达式无效,无法调用helper.TextBoxFor(...)

怎么做?

1 个答案:

答案 0 :(得分:0)

这应该可以满足您的需求:

public static MvcHtmlString TextBoxForAdv<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> value)
        {
            var body = Expression.Property(value.Body, "Name");
            var expression = Expression.Lambda<Func<TModel, string>>(body, value.Parameters[0]);
            return helper.TextBoxFor(expression);
        }