and*_*dko 2 c# asp.net asp.net-mvc asp.net-mvc-4
我需要使用局部视图在Layout中渲染菜单(如果有更好的方法,请告诉我)。我这样做(在布局中):
@if (User.IsInRole("Admin"))
{
@Html.Partial("AdminMenu")
}
Run Code Online (Sandbox Code Playgroud)
这就是我在Controller中的称呼方式:
public ActionResult AdminMenu()
{
var am = _amr.GetAdminMenu();
return PartialView(am);
}
Run Code Online (Sandbox Code Playgroud)
所以这是我的部分观点:
@model IEnumerable<DigitalHubOnlineStore.ViewModels.AdminMenuViewModel>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Admin menu
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
@foreach (var item in Model)
{
<li><a href="@Html.DisplayFor(modelItem => item.MenuItemUrl)">@Html.DisplayFor(modelItem => item.MenuItemName)</a></li>
}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
Unfortunately it's not working.
You need to use
@{Html.RenderPartial("Admin");}
Run Code Online (Sandbox Code Playgroud)
Html.Partial only returns the view as a string, it does not write it to the response, so just calling it does nothing, the returned string falls out of scope. The reason for it's existince is so you can render a partial view to a string and then insert the string in multiple places without having to render the partial view multiple times. For example if you want the same paging markup to be at the top and bottom of the page. Or maybe you want to duplicate a Tab Partial view to create multiple tabs, etc etc etc.
To get your current code to work, try this
Model ......
@{
Layout=.....
var adminMenu = Html.Partial("Admin");
}
@if (User.IsInRole("Admin"))
{
Html.Raw(adminMenu);
}
Run Code Online (Sandbox Code Playgroud)
Html.RenderPartial does the same thing but internally calls Write to write it to the response.
Now if your Partial Is Accepting a model then you need to give it a controller method,
[ChildActionOnly]
public ActionResult AdminMenu(AdminMenuViewModel model)
{
return Partial(model);
}
Run Code Online (Sandbox Code Playgroud)
Then update your calling code to,
@{Html.RenderAction("AdminMenu", "ControllerHere", new { model = TheAdminViewModelHere });}
Run Code Online (Sandbox Code Playgroud)
我个人希望对部分视图使用ChildOnlyAction,因为我可以将所有处理逻辑移至部分视图的控制器中,这样性能更好。它还允许局部视图了解有关其父上下文的信息,因为它使您可以访问控制器以向模型添加信息以传递至局部视图。
| 归档时间: |
|
| 查看次数: |
19422 次 |
| 最近记录: |