繁体   English   中英

ASP.NET MVC –数据库驱动菜单

[英]ASP.NET MVC – Database Driven Menu

我有一个数据库菜单结构,我想添加到site.master文件中。

我在StackOverflow上查看了其他问题,但无法在我的网站上使用。

如何将用户控件添加到Site.Master文件?

Menu.ascx

<%foreach (MainMenuSort mainMenuSort in (List<MainMenuSort>)ViewData["MainMenuSortListDisplay"])
      { %>
         <li><%= Html.Encode(mainMenuSort.MainMenuId.MainMenuName)%></li>
         <%foreach (SubMenuSort subMenuSort in (List<SubMenuSort>)ViewData["SubMenuSortListDisplay"])
           {%>
            <%if (mainMenuSort.MainMenuId.Id == subMenuSort.SubMenuId.MainMenu.Id)
              { %>
              <li><%= Html.Encode(subMenuSort.SubMenuId.SubMenuName)%></li>
            <%} %>
         <%} %>
      <%}%>

您需要在母版页中使用Html.RenderPartial方法。

您需要在调用使用母版页的视图的任何操作中设置MainMenuSortListDisplay和SubMenuSortListDisplay视图数据键。

在您的主人中使用

<% Html.RenderPartial("~/Views/Shared/Menu.ascx");

该路径必须是应用程序相对于控件文件夹的相对路径。 通常,这些位于“共享”下。 您可以根据需要在“共享”文件夹下进行结构设计。

为了使此技术更强壮,请使用强类型的partial。 在问题中,您可能会创建一个具有两个通用集合作为属性的新类(MenuModel),并将其放置在应用程序的models文件夹中。 然后,在模型的构造函数中调用填充列表的方法。

public class MenuModel
{
   public IEnumerable<MainMenuSort> OuterList {get; set;}
   public IEnumerable<SubMEnuSort> InnerList {get; set;}
   public MenuModel()
   {
       VoidThatFillsTheInnerAndOuterList();
   }

这意味着您可以在控制器中执行此操作

public ActionResult ShowAForm()
{
   ViewData["MenuPartialData"] = new MenuModel();
   return View();
}

设置此键后,您的母版页可以使用RenderPartial的重载,如下所示

<% Html.RenderPartial(
    "~/View/Shared/Menu.ascx", 
    (MenuModel)ViewData["MenuPartialData"]); %>

假定您的Partial是强烈键入MenuModel类的。 然后,在部分代码中,您可以使用稍微重写代码的模型

<% foreach (MainMenuSort mainMenuSort in Model.OuterList) { %>
     <li><%= Html.Encode(mainMenuSort.MainMenuId.MainMenuName)%></li>
     <% foreach (SubMenuSort subMenuSort in Model.InnerList) {%>            
        <%if (mainMenuSort.MainMenuId.Id == subMenuSort.SubMenuId.MainMenu.Id)  
        { %>              
           <li><%= Html.Encode(subMenuSort.SubMenuId.SubMenuName)%></li>
      <%} %>
     <%} %>      
    <%}%>

希望能有所帮助

尝试类似

<% Html.RenderPartial("Menu") %>

编辑:纠正了错字

您也可以将其用作HTMLHelper,并在MasterPage中仅调用<%= Html.Menu()%>。 然后,在HTMLHelper中,您将获得获取数据库记录并遍历它们的代码。 这是我找到的入门链接 请注意我的评论,因为所提供的代码示例中存在错误。 我在处理菜单子项时仍然遇到问题,我想我需要递归函数之类的东西吗?

借助此链接 我能够在site.master页面中显示菜单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM