ASP MVC:以编程方式创建Expression <func <tmodel,tvalue =“” >>表达式

时间:2018-06-29 13:44:21

标签: c# asp.net-mvc

我想生成具有该功能的MVC编辑器

System.Web.Mvc.Html.EditorExtensions.EditorFor<TModel, TValue>(
       this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, 
       object htmlAttributes = null)

问题是

Expression<Func<TModel, TValue>> expression

因为我只有属性的名称。我确定该属性存在,并且可以获得模型的实际实例。

如何创建正确的参数?

编辑:为了更加清楚: 我有模型,我有属性的名称,想创建Expression>。

谢谢!

彼得

2 个答案:

答案 0 :(得分:1)

如果将属性名称作为字符串,请使用Editor扩展方法,而不要使用EditorFor

例如

@Html.Editor("YourProperty", new { htmlAttributes = new { ..

答案 1 :(得分:0)

Johnathan Barclay的答案为我提供了正确的指导!

我现在使用html.Editor代替html.Editor。

这里是生成器类代码的摘录:

 public static MvcHtmlString GenerateStepTwo(this HtmlHelper<InputModell> html, InputModell modell)
    {
     ...
     foreach (var actField in fieldsSorted)
        {
        ...
        editor = html.Editor(fieldname, new { htmlAttributes = new { @class = "form-control", style = "max-width:200px;min-width:100px" } });

        all.AppendLine(AddOpenImageFunc(editor, fieldname));
...
}
return all;

谢谢! 彼得