ASP.NET MVC Menu Selected Item

前端 未结 7 1428
夕颜
夕颜 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("", isCurrentRoute ? " class=\"YourActiveCssClass\"" : string.Empty) + actionLink + "
  • "); } } }

    Layout page

    
    

提交回复
热议问题