ASP.NET MVC Menu Selected Item

前端 未结 7 1429
夕颜
夕颜 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:40

    The answer from Jakub Konecki led me in the right direction... here is the controller action I ended up with:

        [ChildActionOnly]
        public ActionResult MainMenu()
        {
            var items = new List
            {
                new MenuItem{ Text = "Home", Action = "Index", Controller = "Home", Selected=false },
                new MenuItem{ Text = "My Profile", Action = "Index", Controller = "Profile", Selected = false},
                new MenuItem{ Text = "About", Action = "About", Controller = "Home", Selected = false }
            };
    
            string action = ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
            string controller = ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString();
    
            foreach (var item in items)
            {
                if (item.Controller == controller && item.Action == action)
                {
                    item.Selected = true;
                }
            }
    
            return PartialView(items);
        }
    

    Hope this helps someone.

提交回复
热议问题