gpt4 book ai didi

asp.net - 所有局部 View 的自定义 ActionResult 等效模型

转载 作者:行者123 更新时间:2023-12-03 15:01:48 25 4
gpt4 key购买 nike

我创建了以下自定义 ActionResult它返回多个局部 View 。

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 并将其分配给变量。然后您会注意到它们都共享等效模型。

最佳答案

您可以初始化 MultiplePartialViewsResult 以以下方式使用 对象全新 查看数据 / ViewData.Model 实例(对我来说很好用):

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);
}
}
}

Controller :
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>

关于asp.net - 所有局部 View 的自定义 ActionResult 等效模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com