ASP.NET MVC 3: How to get the current controller and action in a Razor view


The following code snippet enables you to access the name of the controller and the action that are processing the (current) request:

Controller: @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

View: @ViewContext.Controller.ValueProvider.GetValue("action").RawValue
,

9 responses to “ASP.NET MVC 3: How to get the current controller and action in a Razor view”

  1. You should look up these values in the controller and pass them to the view.

    Current controller

    var rd = ControllerContext.RouteData;
    var currentAction = rd.GetRequiredString(“action”);
    var currentController = rd.GetRequiredString(“controller”);

    Partial view controller

    var rd = ControllerContext.ParentActionViewContext.RouteData;
    var currentAction = rd.GetRequiredString(“action”);
    var currentController = rd.GetRequiredString(“controller”);

  2. Cntrl= ViewContext.RouteData.Values[“controller”].ToString();
    Action = ViewContext.RouteData.Values[“action”].ToString();

  3. The title of this is incorrect, it does not get the current controller and action, it gets their names.

Leave a Reply

Your email address will not be published. Required fields are marked *