我创建了一个 htmlhelper 扩展,以减少创建表单时重复标记的数量:
public static MvcHtmlString RenderField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
return htmlHelper.DisplayFor(expression, "formfield");
}
想法是在我的视图中我可以写@Html.RenderField(x=>x.MyFieldName)
并且它将打印标签和字段的内容,并且已经有适当的div
标签。
在 displaytemplates 文件夹中,我创建了包含以下内容的 formfield.cshtml:
<div class="display-group">
<div class="display-label">
@Html.LabelFor(x => x)
</div>
<div class="display-field">
@Html.DisplayFor(x => x)
</div>
</div>
不幸的是,似乎没有可能在显示模板中嵌套 DisplayFor(它不会渲染任何东西)。我不想只使用@Model
因为那时我不会得到布尔值的复选框,日期等的日历控件。
这有什么好办法吗?
1 回答
你不能嵌套
DisplayFor()
。看这里:是否可以在 EditorFor 模板控件中使用 DisplayFor()你考虑过
Html.DisplayForModel()
吗?可在此处找到说明和示例代码:http://msdn.microsoft.com/en-us/library/ee430907(v=VS.100).aspx