ASP.NET MVC Menu Selected Item

前端 未结 7 1427
夕颜
夕颜 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 19:04

    More simplest way when you don't want to change your code much .. Thanks @Hugo Hilário for the concept

    using Microsoft.Web.Mvc;     
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    namespace Demo.Web.Mvc
    {
        public static class UIHelper
        {             
            public static MvcHtmlString ActivePage(this HtmlHelper helper, string linkText, string action, string controller)
            { 
                string currentController = helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
                string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();    
    
                var actionLink = helper.ActionLink(linkText, action,controller);
                var isCurrentRoute = currentController == controller;// && currentAction == action; uncomment if you want to segregate by action also
    
                return MvcHtmlString.Create(string.Format("<li{0}>", isCurrentRoute ? " class=\"YourActiveCssClass\"" : string.Empty) + actionLink + "</li>");    
    
            }
        }
    }
    

    Layout page

    <div class="navbar-collapse collapse">
         <ul class="nav navbar-nav"> 
              @Html.ActivePage("User", "Index", "User") 
              @Html.ActivePage("State", "Index", "State") 
              @Html.ActivePage("City", "Index", "City") 
         </ul>                     
    </div>
    
    0 讨论(0)
提交回复
热议问题