在一个编辑器模板中调用另一个具有相同模型的编辑器模板 [英] In an Editor Template call another Editor Template with the same Model

查看:29
本文介绍了在一个编辑器模板中调用另一个具有相同模型的编辑器模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. EditorTemplatesTemplate1.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")

和 EditorTemplatesTemplate2.cshtml

and EditorTemplatesTemplate2.cshtml

@model foo

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

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

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.

推荐答案

简短回答:

改用Html.Partial.

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

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)

长答案:

遗憾的是,这似乎是设计使然.MVC 跟踪已经渲染的模型,如果你的模型已经被模板渲染过,它不会重复渲染,即使模板不同.因此,为什么第二个 @Html.EditorForModel("Template2") 什么都不做.

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.

具体来说,它是在 ViewData.TemplateInfo.VisitedObjects 中跟踪的,这是一个内部字段,因此您在事后修改它是没有希望的.该字段的目的是防止无限递归.高尚,但很烦人,因为它没有考虑使用的模板.

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.

我通过查看 源代码,这对于发现 MVC 的这些奇怪的特质非常有用.

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

这篇关于在一个编辑器模板中调用另一个具有相同模型的编辑器模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆