I need to put couple drop down menus on the upper right hand side of my application. These menus need to appears on every page where that layout is used.
The only problem is that items of the menu are pulled from a database.
Usually I would pass the list to the model like so
public ActionResult Clients()
{
using (SomeContext db = new SomeContext())
{
var clients = db.Database.SqlQuery<Client>("SELECT * FROM clients").ToList();
return View(clients);
}
}
But, I am not sure how to do the same thing without having to write the same code for every view. I want to only write this code below once and not worry about having to write the same code for every view.
What is the right way to have a global drop down menu for my application?
I prefer to use an controller to render my menu. This provides caching, reuse and logic for a menu (like showing or not showing a menu based on roles/claims). You can read the complete article by Phil Haacked - Html.RenderAction and Html.Action, excerpt below.
c#
Html:
You can create an action filter to do this.
Assuming you have a class called
MenuItem
Now, if you want this in every page, just register it globally. You can do this in the
RegisterRoutes
method inRouteConfig
classNow in your Layout file, read the ViewBag item called Menus and build the menu markup as needed.
You may update the above code to render
Childs
as needed.