asp.net-mvc MVC:如何让控制器呈现从视图启动的部分视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29380011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC: How to get controller to render partial view initiated from the view
提问by brinch
In my MVC5 project I want to create a menu in a partial view. This menu is dynamic in the sense that it is built from content in my database. Thus I have a controller taking care of creating my menu and returning the menu model to my partial view:
在我的 MVC5 项目中,我想在局部视图中创建一个菜单。这个菜单是动态的,因为它是根据我的数据库中的内容构建的。因此,我有一个控制器负责创建我的菜单并将菜单模型返回到我的局部视图:
public PartialViewResult GetMenu()
{
MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();
return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel);
}
In my partial view called MenuPartialI want to use razor to iterate over my menu items, like:
在名为MenuPartial 的局部视图中,我想使用 razor 来迭代我的菜单项,例如:
@model MyApp.Models.Menu.MenuStructuredModel
<div class="list-group panel">
@foreach (var category in Model.ViewTypes[0].Categories)
{
<a href="#" class="list-group-item lg-green" data-parent="#MainMenu">@category.ShownName</a>
}
</div>
Now the problem is the view in which I insert the partial view. If in the view I simply do:
现在的问题是我插入局部视图的视图。如果在视图中我只是这样做:
@Html.Partial("MenuPartial")
It won't call the controller to populate the model with data first. What I want is to let the controller return the partial. But I don't know how to do this from the view. In pseudo code I would like to do something like:
它不会先调用控制器用数据填充模型。我想要的是让控制器返回部分。但我不知道如何从视图中做到这一点。在伪代码中,我想做类似的事情:
@Html.RenderPartialFromController("/MyController/GetMenu")
回答by brinch
Thanks to Stephen Muecke and Erick Cortorreal I got it to work.
感谢 Stephen Muecke 和 Erick Cortorreal,我让它开始工作。
This is what the controller should look like:
控制器应该是这样的:
[ChildActionOnly]
public PartialViewResult GetMenu()
{
MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();
return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel);
}
And it may called like:
它可能被称为:
@Html.Action("GetMenu", "Home")
@Html.Action("GetMenu", "Home")
(Hence GetMenu()is declared in the HomeControllerin my example).
(因此在我的示例中GetMenu()声明HomeController)。
The controller is now called (and the model is populated) prior to the partial view is rendered.
现在在呈现局部视图之前调用控制器(并填充模型)。
回答by Erick Cortorreal
You should use: @Html.RenderActionor @Html.Action.
您应该使用:@Html.RenderAction或@Html.Action。

