模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式

时间:2013-02-04 13:49:02

标签: asp.net asp.net-mvc asp.net-mvc-3 razor asp.net-mvc-4

我的模特:

public class EmployeeModel
{
    [Required]
    [StringLength(50)]
    [Display(Name = "Employee Name")]
    public string EmpName { get; set; }

    [Required]
    [StringLength(150)]
    [Display(Name = "Email Id")]
    public string Email { get; set; }

    [Required]
    [Range(18, 150)]
    public int Age { get; set; }

}

在我看来:

 @Html.MyEditFor(model=>model.EmpName)
 @Html.MyEditFor(model=>model.Email)
 @Html.MyEditFor(model=>model.Age)

我的自定义助手:

public static MvcHtmlString MyEditFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, object>> expression)
    {
        var partial = html.Partial("Item", new LabelEditorValidation() { Label = html.LabelFor(expression), Editor = html.EditorFor(expression), Validation = html.ValidationMessageFor(expression) }).ToString();
        return MvcHtmlString.Create(partial);
    }

Item.cshtml - 局部视图:

 @model MyClientCustomValidation.Models.LabelEditorValidation 
        <tr>
            <td class="editor-label" style="border: 0;">
                @Model.Label
            </td>
            <td class="editor-field" style="border: 0">
                @Model.Editor
                @Model.Validation
            </td>
        </tr>

LabelEditorValidation - Item.cshtml的模型:

      public class LabelEditorValidation
{
    public MvcHtmlString Validation { get; set; }
    public MvcHtmlString Label { get; set; }
    public MvcHtmlString Editor { get; set; }
}

我有例外

  

模板只能用于字段访问,属性访问,   单维数组索引或单参数自定义索引器   表达式

在线:

    var partial = html.Partial("Item", new LabelEditorValidation() { Label = html.LabelFor(expression), Editor = html.EditorFor(expression), Validation = html.ValidationMessageFor(expression) }).ToString();

@Html.MyEditFor调用model.Age时发生异常。

 @Html.MyEditFor(model=>model.Age) 

但是在为@Html.MyEditFormodel.EmpName调用model.Email时却不会发生这种情况。 这是因为model.EmpNamemodel.Email是字符串,但model.Ageint

2 个答案:

答案 0 :(得分:10)

对于Google搜索用户, 只是不要调用任何Html.XyzFor这样的方法

@Html.CheckBoxFor(model => model.Property***.MyMethod()***)

请改用view models,将MyMethod应用于给定的媒体资源。

答案 1 :(得分:7)

你可以让你的助手变得更通用,并摆脱object参数:

public static MvcHtmlString MyEditFor<TModel, TProperty>(
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, TProperty>> expression
)
{
    var partial = html.Partial(
        "Item", 
        new LabelEditorValidation 
        { 
            Label = html.LabelFor(expression), 
            Editor = html.EditorFor(expression), 
            Validation = html.ValidationMessageFor(expression) 
        }
    ).ToString();
    return MvcHtmlString.Create(partial);
}

现在你的表情不会因为赢得不必要的拳击而中断。