在编辑器模板中调用具有相同模型的另一个编辑器模板

发布于 2024-11-26 05:46:01 字数 539 浏览 7 评论 0原文

我有一个编辑器模板,在该编辑器模板中我想调用另一个具有相同模型(即嵌套)的编辑器模板,但它似乎没有显示。
IE。 \EditorTemplates\Template1.cshtml

@model foo

// insert code here to edit the default fields.

// display extra fields via another editor template.
@Html.EditorForModel("Template2")   // or @Html.EditorFor(m => m, "Template2")

和 \EditorTemplates\Template2.cshtml

@model foo

@Html.TextBoxFor(m => m.Name)

我肯定有人会质疑为什么?好吧,只有满足条件时才会显示嵌套模板(即 @if (@Model.IsConditionMet) { .... } ),但为了简单起见,我已将其排除在原型之外。

I have an editor template and within that editor template i want to call another editor template with the same model (i.e. nested), but it does not seem to display.
ie. \EditorTemplates\Template1.cshtml

@model foo

// insert code here to edit the default fields.

// display extra fields via another editor template.
@Html.EditorForModel("Template2")   // or @Html.EditorFor(m => m, "Template2")

and \EditorTemplates\Template2.cshtml

@model foo

@Html.TextBoxFor(m => m.Name)

I am sure someone will question why? Well, the nested template will only be displayed if a condition is met (ie. @if (@Model.IsConditionMet) { .... } ), but I have left that out of my prototype for simplicity.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下凄凉 2024-12-03 05:46:01

简短回答:

使用 Html.Partial 代替。

因此,在您的 Template1.cshtml 文件中:

@model foo

// insert code here to edit the default fields.

// display extra fields via another editor template.
@Html.Partial("EditorTemplates/Template2", Model)

长答案:

遗憾的是,这似乎是设计使然。 MVC 跟踪已渲染的模型,如果您的模型已由模板渲染,则即使模板不同,它也不会执行两次。因此,为什么第二个 @Html.EditorForModel("Template2") 什么也不做。

具体来说,它是在 ViewData.TemplateInfo.VisitedObjects 中跟踪的,这是一个内部字段,因此事后您无法对其进行修改。该字段的目的是防止无限递归。高贵,但令人烦恼的是它没有考虑所使用的模板。

我通过查看 源发现了这一点code,这对于发现 MVC 的这些奇怪特性非常有用。

Short answer:

Use Html.Partial instead.

So, in your Template1.cshtml file:

@model foo

// insert code here to edit the default fields.

// display extra fields via another editor template.
@Html.Partial("EditorTemplates/Template2", Model)

Long answer:

This sadly appears to be by-design. MVC tracks the models that have been rendered, and if your model has already been rendered by a template, it won't do it twice, even if the template is different. Hence why the second @Html.EditorForModel("Template2") just does nothing.

Specifically, it's tracked in ViewData.TemplateInfo.VisitedObjects, which is an internal field, so there's no hope in you modifying it after the fact. The intention of this field is to prevent infinite recursion. Noble, but annoying in that it doesn't take the template used into account.

I found this out by looking at the source code, which is great for finding these weird idiosyncrasies of MVC.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文