ASP.Net MVC控制器_layout [英] ASP.Net MVC Controller for _Layout

查看:258
本文介绍了ASP.Net MVC控制器_layout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的MVC动态菜单系统,只是使它工作,我创建了菜单的局部视图,它使用下面的语法的伟大工程:

  @ Html.RenderPartial(_菜单,(Models.Menu)ViewBag.MainMenu)

但是,要做到这一点,我将不得不设置在ViewBag的主菜单,FooterMenu(或与此有关的任何其他菜单)上的每个控制器和每个动作。为了避免这种情况,我想知道如果有,我可以在全球访问ViewBag推荐的事件。如果没有,有没有人建议通过菜单对象到一个会话变量?这听起来不是我的权利,但我唯一能想到的现在。

更新:

_Layout.cshtml - 我列入到行动新的呼叫:

  @ Html.Action(RenderMenu,SharedController,新的{名=主})

SharedController.cs - 增加了新动作:

 公众的ActionResult RenderMenu(字符串名称)
{
    如果(db.Menus.Count&所述;菜单>()大于0&放大器;&放大器; db.MenuItems.Count&下;菜单项>()&0)
    {
        菜单菜单= db.Menus.Include(的MenuItems),单<菜单>(M = GT; m.Name ==名);
        返回PartialView(_ MenuLayout菜单);
    }
    其他
    {
        返回PartialView(_ MenuLayout,NULL);
    }
}

和它抛出以下异常:


  

有关路径控制器'/'没有被发现,或者不执行
  一个IController。


更新2:

所以,问题是,我的全名中引用的控制器,你只需要在控制器的名字去掉控制器。整齐的珍闻。因此,我的例子,这个作品:

  @ Html.Action(RenderMenu,共享,新的{名=主})


解决方案

设置你的菜单了作为一个动作,然后把它在你的总体布局。

使用@ Html.Action()

动作可以返回在它的菜单code的局部视图。

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)

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.

UPDATE:

_Layout.cshtml - I included the new call to Action:

@Html.Action("RenderMenu", "SharedController", new { name = "Main" })

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);
    }
}

And it throws the following exception:

The controller for path '/' was not found or does not implement IController.

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

use @Html.Action()

the action can return a partial view with your menu code in it.

这篇关于ASP.Net MVC控制器_layout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆