2013-11-21 29 views
2

在布局中,调用MVC子动作。但是,partialView结果不会显示在RenderSection(“userProfile”,必需:false)中。虽然,Watch窗口显示结果包含数据。谢谢。如何渲染MVC子Action Action PartialView到布局@RenderSection()?

控制器的动作

[ChildActionOnly] 
    public ActionResult GetUserProfile() 
    { 
     var vm = base.appVM.User; 
     return PartialView("UserProfilePartial", vm); 
    } 

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

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

回答

0

的主要问题是,你没有渲染的布局的局部视图。当你渲染局部视图时,它只会呈现你指定的代码,但是你创建了一个除了Layout.cshtml之外的任何地方都没有渲染的区域,但是布局不会在任何地方被调用。要解决此问题,您必须将布局代码添加到您的局部视图。

@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

+0

即由包括@创建堆栈溢出{布局=“〜/查看/共享/ _Layout.cshtml“;}。我知道@ Html.Partial()会在调用动作的行中插入片段,但我希望它在布局中的@RenderSection(“userProfile”)所在的行处呈现。 – user266909

+0

...我想在partialView中使用@section userProfile {}。 – user266909

0

你不能在部分视图中使用部分。只有视图支持使用部分。部分视图仅用于显示内容,而不指定函数可以执行的其他功能。有类似的线程有关它请看看它在here

0

确定这里是我是如何做到的

主_ViewStart.cshtml我把这个代码

@{ 
    if (Request["Partial"] == null) 
    { 
     //return full view 
     Layout = "~/Views/Shared/_Layout.cshtml"; 
    } 
    else 
    { 
     //this will give just a partialview with the bodyContent 
     Layout = "~/Views/Shared/_LayoutPartial.cshtml"; 
    } 
} 

然后我可以返回完整的视图,它将返回baseed的部分请求的观点(href=http://www.d.com/account/login?=partial=partial

它只是工作!

通过,你可以在局部布局路段等谐音 添加方式,因为毕竟它只是一个普通的布局

相关问题