我创建了以下自定义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。它使用数组中指定的最后一个模型覆盖所有模型。
尝试在方法中创建几个PartialView并将其分配给变量。那么你会注意到他们都有相同的模式。
解决方法
您可以使用新的自己的ViewData / ViewData.Model实例以下列方式初始化MultiplePartialViewsResult对象(对我来说可以正常工作):
return new MultiplePartialViewsResult( //PartialView("~/Views/RowSumView.cshtml",//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>() { 2.0 }) new PartialViewResult() { ViewName = "~/Views/RowSumView.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>