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.MyEditFor被调用时发生model.EmpNameand model.Email。那是因为model.EmpNameandmodel.Email是字符串但是model.Ageint

4

2 回答 2

10

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

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

改为使用view models,将其应用于MyMethod给定的属性。

于 2013-04-29T18:51:55.737 回答
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);
}

现在你的表情不会中断,因为不会有不必要的拳击。

于 2013-02-04T16:04:23.580 回答