[英]MVC ViewBag for partial view is null
Have a basic question regarding partial view.the @ViewBag.Message comes out empty in the final render. 有一个关于局部视图的基本问题。@ ViewBag.Message在最终渲染中显示为空。
My controller looks like this 我的控制器看起来像这样
public ActionResult Message() {
ViewBag.Message = "This is a partial view.";
return PartialView();
}
public ActionResult PartialViewDemo() {
return View();
}
My partial view looks like this in Message.cshtml 我的部分视图在Message.cshtml中看起来像这样
<h2>@ViewBag.Message</h2>
I am calling the partial view like this from partialViewTest.cshtml. 我从partialViewTest.cshtml调用这样的局部视图。 the @ViewBag.Message is empty and only h2 tag is shown. @ ViewBag.Message为空,仅显示h2标签。
<div>@Html.Partial("~/Views/Sample/Message.cshtml")</div>
If i implement using javascript it works fine 如果我使用JavaScript实施,则效果很好
<div id="result"></div>
@section scripts {
<script type="text/javascript">
$(function () {
$('#result').load('/sample/message');
});
</script>
}
You Render Message.cshtml only (not controller) from partialViewTest.cshtml. 您只能从partialViewTest.cshtml渲染Message.cshtml(而不是控制器)。 As you set ViewBag.Message in the controller, you have to call the controller (to get partial view) like this. 在控制器中设置ViewBag.Message时,必须像这样调用控制器(以获取部分视图)。
@Html.Action("Message", "Sample")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.