Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

asp.net mvc - In an Editor Template call another Editor Template with the same Model

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

and EditorTemplatesTemplate2.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...