我有一个母版页,其中呈现 3 个部分 View ,并且它包含一个用于 View 的渲染主体(内容占位符)。
我正在尝试将数据(任何字符串)从我的 subview 传递到母版页上呈现的部分 View 之一。为此,我使用 Viewbag
但它无法在父 View 上访问。
我的代码如下:
我的母版页:[ Main_Layout.chtml
]
<body>
<div>
@{Html.RenderAction("Header_PartialView", "Home");}
</div>
<div>
<table cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td id="tdLeft" class="lftPanel_Con">
<div>
@{Html.RenderAction("LeftPanel_PartialView", "Home");}
</div>
</td>
<td id="tdRight" width="100%">
<div>
@RenderBody()
</div>
</td>
</tr>
</table>
</div>
<!--start footer-->
<div>
@{Html.RenderAction("Footer_PartialView", "Home");}
</div>
</body>
我的 subview :[ TestPage1.chtml
]
@{
ViewBag.Title = "TestPage1";
Layout = "~/Views/Shared/Main_LayoutPage.cshtml";
var test1 = ViewBag.testData1;
var test2 = ViewData["testData2"];
}
<h2>TestPage1</h2>
<div>This is only for testing</div>
我的 Controller 代码:
public ViewResult TestPage1()
{
ViewBag.testData1 = "My first view bag data";
ViewData["testData2"] = "My second view data";
return View();
}
现在我想在 Header_PartialView
View 上访问 TestPage 的数据。
@{
var test = ViewBag.testData1;
var test2 = ViewData["testData2"];
}
最佳答案
要访问 Header_PartialView 中 TestPage 中的数据,您需要将其作为 Main_LayoutPage.cshtml
上的 Html.RenderAction()
中的参数传递,如下所示:
@{ var test = ViewBag.testData1; }
@{Html.RenderAction("Header_PartialView", "Home", new { test = test });}
并在 Header_PartialView
操作中添加参数 string test
并将其作为模型传递,因为布局中的 ViewBag 不会出现在此处。
public ActionResult Header_PartialView(string test)
{
return View(model: test);
}
然后在 Header_PartialView.cshtml
上您将获得代码:
@model string
@{
Layout = null;
}
<div>@Model</div>
关于asp.net-mvc-3 - 如何在asp net mvc3中将值从部分 View 传递到父 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17652894/