问题
I'm trying to give a model to the shared layout so the menu links are created dynamically from a database. Any ideas where I should start?
I am looking for maybe tutorials of how to use inheritance to do this?
回答1:
You could do this:
Model
public partial class Menu
{
public String[] items;
public Menu(String[] items)
{
this.items = items;
}
}
View (_Menu)
@model YourMVC.Models.Menu
<ul>
@foreach (String item in Model.items)
{
<li>@item</li>
}
</ul>
Place this in _Layout
@Html.Action("_Menu", "Home")
Controller (HomeController)
public ActionResult _Menu()
{
String[] items = {"Item1", "Item2", "Item3", "Item4"};
return PartialView(new Menu(items));
}
Of course in your actual implementation you would grab whatever you needed from the database in the controller _Menu()
action.
I'm not sure if this implementation is the best practice, but it certainly works.
来源:https://stackoverflow.com/questions/8487902/how-to-give-shared-layout-a-model-in-razor-mvc