我的型号:
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; }
}
我有例外
模板只能用于字段访问、属性访问、
单维数组索引,或单参数自定义索引器
表达式
on line:
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
and model.Email
是字符串但是model.Age
is int