Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

menu - ASP.Net MVC Controller for _Layout

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" })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...