ASP.NET MVC Menu Selected Item

前端 未结 7 1431
夕颜
夕颜 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条回答
  •  梦毁少年i
    2021-01-30 18:42

    Here is another possibility, more simple in my opinion using an HTML Helper:

    CSS Class

    ul#menu li.selected a {
      background-color: #034af3;
      color: #e8eef4;
    }
    

    HTML Helper

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MyWebApp.WebUI.HtmlHelpers
    {
      public static class HtmlHelperExtensions
      {
        public static string ActivePage(this HtmlHelper helper, string controller, string action)
        {
          string classValue = "";
    
          string currentController = helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
          string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
    
          if (currentController == controller && currentAction == action)
          {
            classValue = "selected";
          }
    
          return classValue;
        }
      }
    }
    

    Menu on the Layout :

    
    

    More informations here : http://bubblogging.wordpress.com/2012/02/12/mvc-add-selected-class-to-menu/

提交回复
热议问题