How to give shared layout a model in Razor MVC?

﹥>﹥吖頭↗ 提交于 2021-02-04 13:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!