gpt4 book ai didi

asp.net - 为什么 RazorViewEngine 不接收我的 DisplayTemplate?

转载 作者:行者123 更新时间:2023-12-04 15:02:15 26 4
gpt4 key购买 nike

应用程序是一个带有 RAZOR View 引擎的 MVC3 应用程序。

这里使用的 Controller 是 TestController。
我正在使用嵌套 View 。

基本 View (项目列表)是这样的,

//Listing.cshtml
@model ItemsList
@for (int i = 0; i < Model.Items.Count(); i++)
{
@Html.DisplayFor(x => x.Items[i], new { RowPosition = i})
}

这是项目的模板
//Item.cshtml
@model Item
@Html.DisplayFor(x=>x.HeaderText)
@Html.DisplayFor(x=>x, "ItemDetails")

这是项目详细信息的 View
//ItemDetails.cshtml
@model Item
@Html.DisplayFor(x=>x.Description)

所以,我试图将模型从 ITEM 模板传递到 ITEMDETAILS 模板。 ItemDetails.cshtml 位于“Views\Test\DisplayTemplates”下。事实上,我已经尝试将它放在文件夹“Views\Shared”和“Views\Shared\DisplayTemplates”下。但查看引擎似乎只是不捡起来。

但是 Microsoft 文档 here声明 View 引擎确实在 Controller\DisplayTemplates 文件夹中查找以使用使用的 TemplateName 获取 VIEW。

最佳答案

这似乎是 Display/EditorTemplates 的预期行为,大概是为了防止自定义显示模板中的意外无限递归,例如(在 Item.cshtml 中):

@model Item
@Html.DisplayFor(x => x)

...这将无限显示 Item.cshtml显示模板。

显然,在您的示例中,您将项目/模型传递给不同的模板,因此不会导致无限递归。然而,它似乎仍然被框架中的相同安全保护所捕获。不确定它是否会被归类为“错误”或仅仅是“设计使然”?

这是 DisplayFor/TemplateFor helper中的支票:
// Normally this shouldn't happen, unless someone writes their own custom Object templates which 
// don't check to make sure that the object hasn't already been displayed
object visitedObjectsKey = metadata.Model ?? metadata.RealModelType;
if (html.ViewDataContainer.ViewData.TemplateInfo.VisitedObjects.Contains(visitedObjectsKey)) { // DDB #224750
return String.Empty;
}
ViewData.TemplateInfo.VisitedObjects为父模板存储访问过的对象/模型。当你运行时:
@Html.DisplayFor(x => x.Items[i], new { RowPosition = i})

它呈现您的 Item.cshtml DisplayTemplate 并将项目/模型添加到 VisitedObjects .这意味着当 Item.cshtml尝试显示具有相同项目/模型的另一个子模板:
@Html.DisplayFor(x => x, "ItemDetails")

该项目/模型已经在 VisitedObjects ,所以上面的 if 语句返回 true 而不是呈现 ItemDetails.cshtml它只是默默地返回/呈现一个空字符串。

关于asp.net - 为什么 RazorViewEngine 不接收我的 DisplayTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10438958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com