在编辑器模板中调用具有相同模型的另一个编辑器模板
我有一个编辑器模板,在该编辑器模板中我想调用另一个具有相同模型(即嵌套)的编辑器模板,但它似乎没有显示。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短回答:
使用
Html.Partial
代替。因此,在您的 Template1.cshtml 文件中:
长答案:
遗憾的是,这似乎是设计使然。 MVC 跟踪已渲染的模型,如果您的模型已由模板渲染,则即使模板不同,它也不会执行两次。因此,为什么第二个
@Html.EditorForModel("Template2")
什么也不做。具体来说,它是在 ViewData.TemplateInfo.VisitedObjects 中跟踪的,这是一个内部字段,因此事后您无法对其进行修改。该字段的目的是防止无限递归。高贵,但令人烦恼的是它没有考虑所使用的模板。
我通过查看 源发现了这一点code,这对于发现 MVC 的这些奇怪特性非常有用。
Short answer:
Use
Html.Partial
instead.So, in your Template1.cshtml file:
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.