How can I return the current action in an ASP.NET MVC view?

前端 未结 11 1782
旧巷少年郎
旧巷少年郎 2020-11-28 17:32

I wanted to set a CSS class in my master page, which depends on the current controller and action. I can get to the current controller via ViewContext.Controller.GetTy

11条回答
  •  鱼传尺愫
    2020-11-28 18:14

    I know this is an older question, but I saw it and I thought you might be interested in an alternative version than letting your view handle retrieving the data it needs to do it's job.

    An easier way in my opinion would be to override the OnActionExecuting method. You are passed the ActionExecutingContext that contains the ActionDescriptor member which you can use to obtain the information you are looking for, which is the ActionName and you can also reach the ControllerDescriptor and it contains the ControllerName.

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ActionDescriptor actionDescriptor = filterContext.ActionDescriptor;
        string actionName = actionDescriptor.ActionName;
        string controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        // Now that you have the values, set them somewhere and pass them down with your ViewModel
        // This will keep your view cleaner and the controller will take care of everything that the view needs to do it's job.
    }
    

    Hope this helps. If anything, at least it will show an alternative for anybody else that comes by your question.

提交回复
热议问题