Asp.Net MVC: How to determine if you're currently on a specific view

前端 未结 3 1761
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 01:22

I need to determine if I\'m on a particular view. My use case is that I\'d like to decorate navigation elements with an \"on\" class for the current view. Is there a built in

3条回答
  •  醉梦人生
    2021-02-06 02:16

    Here is something a little different, use a FilterAttribute:

        [NavigationLocationFilter("Products")]
        public ViewResult List()
        {
            return View();
        }
    

    ...

    public class NavigationLocationFilterAttribute : ActionFilterAttribute
    {
        public string CurrentLocation { get; set; }
    
        public NavigationLocationFilterAttribute(string currentLocation)
        {
            CurrentLocation = currentLocation;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controller = (Controller)filterContext.Controller;
            controller.ViewData.Add("NavigationLocation", CurrentLocation);
        }
    }
    

    ...

    And in the view:

    <%= ViewData["NavigationLocation"] %>
    

提交回复
热议问题