我的一个 View 中有以下代码片段:
foreach (var topEmployer in Model.TopEmployers)
{
//Some link - works fine for all iterations
@Html.ActionLink(....)
//This partial view is only rendered for the LAST iteration of this loop.
@Html.Partial("partialViewName", topEmployer)
<br />
}
使用调试器单步执行循环(在部分 View 中有一个断点)证实了该问题:调试器仅在最后一次迭代时进入部分 View ,而不是在之前的任何迭代中。看起来它只是忽略了之前迭代的部分 View 。
我不确定如何解决这个问题。曾尝试寻找类似的问题,但没有运气。我做错了什么?
编辑:好的,我将断点放置在未输入的 if 语句内的部分 View 中。所以,这是一个完全不同的问题。部分 View 正在渲染,但由于没有内容,它只是空的,并且断点显然从未被命中。
最佳答案
我尝试重现您的问题,但无济于事。
这是我的主页 Index.cshtml
@model PartialViewForLoop.Controllers.IndexViewModel
@{
ViewBag.Title = "Home Page";
}
@{
foreach (var topEmployer in Model.TopEmployers)
{
//This partial view is only rendered for the LAST iteration of this loop.
@Html.Partial("partialViewName", topEmployer)
<br />
}
}
部分 View
@model string
Hello @Model
和 Controller 代码:
public class HomeController : Controller
{
public ActionResult Index()
{
var vm = new IndexViewModel();
vm.TopEmployers.Add("Mr Tim Jones");
vm.TopEmployers.Add("Mr David Smith");
return View(vm);
}
}
public class IndexViewModel
{
public IndexViewModel()
{
TopEmployers = new List<string>();
}
public IList<string> TopEmployers { get; set; }
}
当我渲染索引 View 时,for 循环执行两次,并且对于每个名称,都会渲染部分 View 。我不明白为什么在您的示例中,部分 View 仅呈现一次。
关于asp.net-mvc - 多次渲染相同的局部 View - 仅渲染最后一个局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26882681/