_Layout 的 ASP.Net MVC 控制器 [英] ASP.Net MVC Controller for _Layout
问题描述
我正在为 MVC 开发一个动态菜单系统,只是为了让它工作,我为菜单创建了一个局部视图,它使用以下语法效果很好:
I am working on a dynamic menu system for MVC and just to make it work, I created a partial view for the menu and it works great using the syntax below:
@Html.RenderPartial("_Menu", (Models.Menu)ViewBag.MainMenu)
但是,要这样做,我必须在每个控制器和每个操作的 ViewBag 中设置 MainMenu 和 FooterMenu(或任何其他与此相关的菜单).为了避免这种情况,我想知道是否有推荐的事件可以让我全局访问 ViewBag.如果没有,是否有人建议将 Menu 对象传递给会话变量?这对我来说听起来不太对,但我现在只能想到这一点.
BUT, to do so, I would have to set the MainMenu and FooterMenu (or any other menu for that matter) in the ViewBag on each Controller and each action. To avoid this, I was wondering if there was a recommended event that I could access the ViewBag globally. If not, does anyone recommend passing the Menu object into a session variable? It doesn't sound right to me, but only thing I can think of right now.
更新:
_Layout.cshtml - 我加入了新的行动呼吁:
_Layout.cshtml - I included the new call to Action:
@Html.Action("RenderMenu", "SharedController", new { name = "Main" })
SharedController.cs - 添加了新操作:
SharedController.cs - Added New Action:
public ActionResult RenderMenu(string name)
{
if (db.Menus.Count<Menu>() > 0 && db.MenuItems.Count<MenuItem>() > 0)
{
Menu menu = db.Menus.Include("MenuItems").Single<Menu>(m => m.Name == name);
return PartialView("_MenuLayout", menu);
}
else
{
return PartialView("_MenuLayout", null);
}
}
它抛出以下异常:
路径/"的控制器未找到或未实现控制器.
The controller for path '/' was not found or does not implement IController.
更新 2:
所以,问题是我通过全名引用了控制器,而您只需要控制器的名称减去控制器".整洁的花絮.所以,对于我的例子,这有效:
So, the issue is that I referenced the Controller by the full name and you only need the name of the controller minus "Controller". Neat tidbit. So, for my example, this works:
@Html.Action("RenderMenu", "Shared", new { name = "Main" })
推荐答案
将您的菜单设置为一个动作,然后在您的主布局中调用它.
set your menu up as an action then call it in your master layout.
使用@Html.Action()
use @Html.Action()
该操作可以返回包含您的菜单代码的部分视图.
the action can return a partial view with your menu code in it.
这篇关于_Layout 的 ASP.Net MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!