问题描述
在布局中,MVC子动作在中调用.但是,partialView结果未显示在RenderSection("userProfile",required:false)中.但是,监视"窗口显示结果中包含数据.谢谢.
In the layout, MVC child actions are called in . However, the the partialView results are not shown in the RenderSection("userProfile", required:false). The Watch window shows the result contains data, though. Thanks.
控制器的动作
[ChildActionOnly]
public ActionResult GetUserProfile()
{
var vm = base.appVM.User;
return PartialView("UserProfilePartial", vm);
}
UserProfilePartial.cshtml
UserProfilePartial.cshtml
@model myApp.viewModel
@section userProfile{
<div>@string.Format("{0}, {1}", Model.lastName, Model.firstName)</div>
@foreach (var item in Model.Locations)
{
<div>
<ul class="row">
<li class="cell">@item.LocType</li>
<li class="cell">@item.LocName</li>
<li class="cell">@item.UserRole</li>
</ul>
</div>
}
}
Layout.cshtml
Layout.cshtml
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">@Html.ActionLink("Home", "Index", "Home")</p>
</div>
@Html.Action("GetUserProfile","User")
<div class="float-right">
@RenderSection("userProfile", required: false)
</div>
@Html.Action("Index", "Menu");
<div class="menu">
@RenderSection("menu", required:false)
</div>
</div>
</header>
@RenderBody()
</body>
推荐答案
主要问题是您正在渲染不带布局的局部视图.渲染部分视图时,它将仅渲染您指定的代码,但是您创建了一个节,该节除了Layout.cshtml之外均未渲染,但是布局未在任何地方调用.要解决此问题,您必须将布局代码添加到局部视图中.
The main issue is that you are rendering a partial view without a layout. When you render the partial view it will only render the code you specify, however you created a section that is not rendered anywhere except the Layout.cshtml however the layout is not invoked anywhere. To fix this you have to add the layout code to your partial view.
@model myApp.viewModel
@{
Layout = "~/Views/Shared/Layout.cshtml"; // <---- adding the layout
}
@section userProfile{
<div>@string.Format("{0}, {1}", Model.lastName, Model.firstName)</div>
@foreach (var item in Model.Locations)
{
<div>
<ul class="row">
<li class="cell">@item.LocType</li>
<li class="cell">@item.LocName</li>
<li class="cell">@item.UserRole</li>
</ul>
</div>
}
}
考虑到这一点,我认为您应该使用@ Html.Partial(");不是渲染部分.请查看此链接,例如 http://mvc4beginner.com/Tutorial/MVC- Partial-Views.html
After thinking about this i think you should be using @Html.Partial("");not Render section.Take a look at this link for example http://mvc4beginner.com/Tutorial/MVC-Partial-Views.html
这篇关于如何将MVC子动作PartialView呈现为Layout @RenderSection()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!