我创建了以下自定义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() { 1.0 }), PartialView("~/Views/ColumnSumView.cshtml", new List () { 2.0 }));
但是,如果我在MultiplePartialViewsResult
构造函数中放置断点,我会看到两种情况下的模型等于2.0
.它使用数组中指定的最后一个模型覆盖所有模型.
尝试在方法中创建几个PartialViews并将其分配给变量.然后你会注意到他们都拥有相同的模型.
您可以使用新的ViewData/ViewData.Model实例以下列方式初始化MultiplePartialViewsResult对象(对我来说很好):
return new MultiplePartialViewsResult( //PartialView("~/Views/RowSumView.cshtml", new List() { 1.0 }), //PartialView("~/Views/ColumnSumView.cshtml", new List () { 2.0 }) new PartialViewResult() { ViewName = "~/Views/RowSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List () { 1.0 } } }, new PartialViewResult() { ViewName = "~/Views/ColumnSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List () { 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() { 1.0 }), //PartialView("~/Views/ColumnSumView.cshtml", new List () { 2.0 }) new PartialViewResult() { ViewName = "~/Views/RowSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List () { 1.0 } } }, new PartialViewResult() { ViewName = "~/Views/ColumnSumView.cshtml", ViewData = new ViewDataDictionary() { Model = new List () { 2.0 } } } ); }
浏览次数:
指数:
@Html.Action("FakeAction")
ColumnSumView.cshtml/RowSumView.cshtml:
@model List@foreach(double item in Model) {
- @item
}