如何在Razor MVC中为共享布局提供模型? [英] How to give shared layout a model in Razor MVC?
本文介绍了如何在Razor MVC中为共享布局提供模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为共享布局提供模型,以便从数据库动态创建菜单链接.有什么想法我应该从哪里开始?
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?
推荐答案
您可以执行以下操作:
模型
public partial class Menu
{
public String[] items;
public Menu(String[] items)
{
this.items = items;
}
}
查看(_Menu)
@model YourMVC.Models.Menu
<ul>
@foreach (String item in Model.items)
{
<li>@item</li>
}
</ul>
将其放置在_Layout
@Html.Action("_Menu", "Home")
控制器(HomeController)
public ActionResult _Menu()
{
String[] items = {"Item1", "Item2", "Item3", "Item4"};
return PartialView(new Menu(items));
}
当然,在实际的实现中,您可以通过控制器 _Menu()
操作从数据库中获取所需的任何内容.
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.
这篇关于如何在Razor MVC中为共享布局提供模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文