首页 文章

在显示模板中使用 DisplayFor

提问于
浏览
4

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

相关问题