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

前端 未结 11 1735
旧巷少年郎
旧巷少年郎 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 17:54

    To get the current Id on a View:

    ViewContext.RouteData.Values["id"].ToString()
    

    To get the current controller:

    ViewContext.RouteData.Values["controller"].ToString() 
    
    0 讨论(0)
  • 2020-11-28 17:59

    Override this function in your controller

    protected override void HandleUnknownAction(string actionName) 
    {  TempData["actionName"] = actionName;
       View("urViewName").ExecuteResult(this.ControllerContext);
    }
    
    0 讨论(0)
  • 2020-11-28 18:05

    You can get these data from RouteData of a ViewContext

    ViewContext.RouteData.Values["controller"]
    ViewContext.RouteData.Values["action"]
    
    0 讨论(0)
  • 2020-11-28 18:06

    In the RC you can also extract route data like the action method name like this

    ViewContext.Controller.ValueProvider["action"].RawValue
    ViewContext.Controller.ValueProvider["controller"].RawValue
    ViewContext.Controller.ValueProvider["id"].RawValue
    

    Update for MVC 3

    ViewContext.Controller.ValueProvider.GetValue("action").RawValue
    ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
    ViewContext.Controller.ValueProvider.GetValue("id").RawValue
    

    Update for MVC 4

    ViewContext.Controller.RouteData.Values["action"]
    ViewContext.Controller.RouteData.Values["controller"]
    ViewContext.Controller.RouteData.Values["id"]
    

    Update for MVC 4.5

    ViewContext.RouteData.Values["action"]
    ViewContext.RouteData.Values["controller"]
    ViewContext.RouteData.Values["id"]
    
    0 讨论(0)
  • 2020-11-28 18:08

    I am using ASP.NET MVC 4, and this what worked for me:

    ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue
    ControllerContext.Controller.ValueProvider.GetValue("action").RawValue
    
    0 讨论(0)
  • 2020-11-28 18:09

    In MVC you should provide the View with all data, not let the View collect its own data so what you can do is to set the CSS class in your controller action.

    ViewData["CssClass"] = "bold";
    

    and pick out this value from your ViewData in your View

    0 讨论(0)
提交回复
热议问题