C# 迭代从AbstractViewModel和DisplayTemplates派生的ViewModels集合将呈现这两个DisplayTemplates
(为头衔道歉……很难确定) 我遇到一种情况,控制器将构建一个列表,其中包含一组从抽象基类派生的ViewModels。然后,我使用显示模板适当地呈现内容,但当我导航到url时,整个内容似乎呈现了两次。这是我的密码C# 迭代从AbstractViewModel和DisplayTemplates派生的ViewModels集合将呈现这两个DisplayTemplates,c#,model-view-controller,display-templates,C#,Model View Controller,Display Templates,(为头衔道歉……很难确定) 我遇到一种情况,控制器将构建一个列表,其中包含一组从抽象基类派生的ViewModels。然后,我使用显示模板适当地呈现内容,但当我导航到url时,整个内容似乎呈现了两次。这是我的密码 public abstract class AbstractItemViewModel { } public class TypeAViewModel : AbstractItemViewModel { public int ID { get; set; } publi
public abstract class AbstractItemViewModel
{
}
public class TypeAViewModel : AbstractItemViewModel
{
public int ID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
public class TypeBViewModel : AbstractItemViewModel
{
public string Title { get; set; }
public List<string> Items { get; set; }
}
。。这里是风景
@using xxx.ViewModels
@model List<AbstractItemViewModel>
@{
ViewBag.Title = "Home";
}
<h1>@Model.Count()</h1>
<div class="container">
<div class="row">
@foreach (AbstractItemViewModel item in Model)
{
<div class="col-xs-12">
@Html.DisplayForModel(item)
</div>
<p>space</p>
}
</div>
</div>
@使用xxx.ViewModels
@模型列表
@{
ViewBag.Title=“主页”;
}
@Model.Count()
@foreach(模型中的AbstractItemViewModel项)
{
@Html.DisplayForModel(项目)
空间
}
。。和2个显示模板
TypeAViewModel.cshtml
@using xxx.ViewModels
@model TypeAViewModel
<h2>@Model.Title (@Model.ID)</h2>
<p>@Model.Body</p>
@using xxx.ViewModels
@model TypeBViewModel
<h2>@Model.Title</h2>
<ul>
@foreach (string s in Model.Items)
{
<li>@s</li>
}
</ul>
@使用xxx.ViewModels
@模型类型aviewmodel
@Model.Title(@Model.ID)
@模特。身体
。。而且。。。
TypeBViewModel.cshtml
@using xxx.ViewModels
@model TypeAViewModel
<h2>@Model.Title (@Model.ID)</h2>
<p>@Model.Body</p>
@using xxx.ViewModels
@model TypeBViewModel
<h2>@Model.Title</h2>
<ul>
@foreach (string s in Model.Items)
{
<li>@s</li>
}
</ul>
@使用xxx.ViewModels
@模型类型bVIEWMODEL
@模型名称
@foreach(Model.Items中的字符串s)
{
- @
}
作为我得到的输出
二,
测试A(1)这是一些身体内容
测试B第1行第2行第3行空间
测试A(1)这是一些身体内容
测试B第1行第2行第3行空间
正如您所看到的,它似乎将整个内容渲染了两次。我已经放置了一个断点,并以绝对不会重复循环的方式遍历了索引视图。有人看到我遗漏了什么吗?您应该使用
DisplayFor
Html帮助程序,而不是DisplayForModel
,因为DisplayForModel
会发送整个模型(在本例中,传入模型的完整列表-AbstractItemViewModel
的后代;item
实际上只是传入模型的附加数据)实际上,对于foreach中的每个项目,完整的模型都会传递到视图中;例如,如果列表中有3个模型,则每个模型将被渲染3次(如果是4次,则渲染4次,以此类推)
为此,请使用以下帮助程序:@Html.DisplayFor(model=>item)
在foreach语句中,而不是DisplayForModel