在显示模板中使用DisplayFor

时间:2011-06-23 13:20:44

标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3

我创建了一个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 个答案:

答案 0 :(得分:2)

您无法嵌套DisplayFor()。见这里:Is it possible to use DisplayFor() from within the EditorFor template control

您考虑过Html.DisplayForModel()了吗?可在此处找到说明和示例代码:http://msdn.microsoft.com/en-us/library/ee430907(v=VS.100).aspx

相关问题