ASP.NET MVC Menu Selected Item

前端 未结 7 1506
夕颜
夕颜 2021-01-30 18:29

OK new to MVC. I had asked this question earlier and got an answer but I am wondering if there is a simpler solution.

Say I have a master page with a menu laid out as an

7条回答
  •  情话喂你
    2021-01-30 18:48

    stephen,

    here's my contribution to the party. a recursive inline function to populate the

    • for as many depths as is required (here's the entire ascx file):

      <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl>" %>
      <%@ Import Namespace="GBC_Art.Controllers" %>
      <%
          Action, int> printNodesRecursively = null;
          printNodesRecursively = (List nodeList, int depth) =>
          {
              if (nodeList == null || nodeList.Count == 0) return;
      %>
          >  
      <%
          foreach (var menuItem in nodeList)
          {
          %>
          
    • <%= Html.ActionLink(menuItem.Text, menuItem.Action, menuItem.Controller, null, new { @class = menuItem.Selected ? "selected" : "" })%> <%printNodesRecursively(menuItem.SubMenu, depth + 1);%>
    • <% } %>
    <% }; List nodes = Model; printNodesRecursively(nodes, 0); %>

    usage -> called as a partialview via the controller as per your example above.

    cheers

提交回复
热议问题