【问题标题】:Using DisplayFor inside a display template在显示模板中使用 DisplayFor
【发布时间】:2011-06-23 13:20:44
【问题描述】:

我创建了一个 htmlhelper 扩展来减少创建表单时重复标记的数量:

public static MvcHtmlString RenderField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
    return htmlHelper.DisplayFor(expression, "formfield");
}

我的想法是在我的视图中我可以只写@Html.RenderField(x=&gt;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,因为那样我就不会得到布尔值的复选框、日期的日历控件等。

有什么好的办法吗?

【问题讨论】:

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


    【解决方案1】:

    你不能嵌套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

    【讨论】:

    • 你的意思是 Html.DisplayForModel() 带参数吗?因为没有它,如果它在 DisplayTemplate 中工作,我希望它能够执行无限递归之类的操作
    猜你喜欢
    • 2011-04-28
    • 2013-08-23
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多