我的模型:
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.EmpName
and model.Email
。那是因为model.EmpName
andmodel.Email
是字符串但是model.Age
是int