MVC:如何获取控制器以呈现从视图启动的部分视图 [英] MVC: How to get controller to render partial view initiated from the view
问题描述
在我的MVC5项目中,我想在局部视图中创建菜单.该菜单是动态的,因为它是根据数据库中的内容构建的.因此,我有一个控制器负责创建菜单并将菜单模型返回到我的局部视图:
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:
public PartialViewResult GetMenu()
{
MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();
return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel);
}
在名为 MenuPartial 的局部视图中,我想使用剃刀迭代菜单项,例如:
In my partial view called MenuPartial I want to use razor to iterate over my menu items, like:
@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")
推荐答案
多亏了Stephen Muecke和Erick Cortorreal,我才开始工作.
Thanks to Stephen Muecke and Erick Cortorreal I got it to work.
这是控制器的外观:
[ChildActionOnly]
public PartialViewResult GetMenu()
{
MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();
return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel);
}
它可能像这样:
@Html.Action("GetMenu", "Home")
(因此在我的示例中的HomeController
中声明了GetMenu()
).
(Hence GetMenu()
is declared in the HomeController
in my example).
现在在渲染局部视图之前调用控制器(并填充模型).
The controller is now called (and the model is populated) prior to the partial view is rendered.
这篇关于MVC:如何获取控制器以呈现从视图启动的部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!