我的模特:
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
调用model.Email
时却不会发生这种情况。
这是因为model.EmpName
和model.Email
是字符串,但model.Age
是int
答案 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);
}
现在你的表情不会因为赢得不必要的拳击而中断。