我创建了以下自定义ActionResult
,它返回多个部分视图。
public class MultiplePartialViewsResult : ActionResult
{
private const string Separator = "-";
private PartialViewResult[] _partialViews;
public MultiplePartialViewsResult(params PartialViewResult[] partialViews)
{
_partialViews = partialViews;
}
public override void ExecuteResult(ControllerContext context)
{
foreach (var partialView in _partialViews)
{
partialView.ExecuteResult(context);
context.HttpContext.Response.Output.Write(Separator);
}
}
}
然后我按如下方式使用它:
return new MultiplePartialViewsResult(
PartialView("~/Views/RowSumView.cshtml", new List<double>() { 1.0 }),
PartialView("~/Views/ColumnSumView.cshtml", new List<double>() { 2.0 }));
但是如果我在MultiplePartialViewsResult
的构造函数中放置断点,我会发现两种情况下的模型都等于2.0
。它使用数组中指定的最后一个模型覆盖所有模型。
尝试在方法中创建几个PartialViews并将其分配给变量。然后你会发现它们都有相同的模型。
答案 0 :(得分:6)
您可以使用新拥有 ViewData / ViewData.Model 实例,按以下方式初始化 MultiplePartialViewsResult 对象(对我来说很好):
return new MultiplePartialViewsResult(
//PartialView("~/Views/RowSumView.cshtml", new List<double>() { 1.0 }),
//PartialView("~/Views/ColumnSumView.cshtml", new List<double>() { 2.0 })
new PartialViewResult() { ViewName = "~/Views/RowSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List<double>() { 1.0 } } },
new PartialViewResult() { ViewName = "~/Views/ColumnSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List<double>() { 2.0 } } }
);
自定义操作结果:
public class MultiplePartialViewsResult : ActionResult {
private const string Separator = "-";
private PartialViewResult[] _partialViews;
public MultiplePartialViewsResult(params PartialViewResult[] partialViews) {
_partialViews = partialViews;
}
public override void ExecuteResult(ControllerContext context) {
foreach(var partialView in _partialViews) {
partialView.ExecuteResult(context);
context.HttpContext.Response.Output.Write(Separator);
}
}
}
<强>控制器:强>
public ActionResult Index() {
return View();
}
public ActionResult FakeAction() {
return new MultiplePartialViewsResult(
//PartialView("~/Views/RowSumView.cshtml", new List<double>() { 1.0 }),
//PartialView("~/Views/ColumnSumView.cshtml", new List<double>() { 2.0 })
new PartialViewResult() { ViewName = "~/Views/RowSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List<double>() { 1.0 } } },
new PartialViewResult() { ViewName = "~/Views/ColumnSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List<double>() { 2.0 } } }
);
}
<强>查看:强>
<强>索引:强>
@Html.Action("FakeAction")
ColumnSumView.cshtml / RowSumView.cshtml:
@model List<double>
<ul>
@foreach(double item in Model) {
<li>@item</li>
}
</ul>