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
<br />
View: @ViewContext.Controller.ValueProvider.GetValue("action").RawValue

Comments

  1. Nick

    Good post. How do you get the current area name? Nick

  2. Ed Lazor

    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”);

  3. ranu mandan

    thx

  4. lijo

    Cntrl= ViewContext.RouteData.Values["controller"].ToString();
    Action = ViewContext.RouteData.Values["action"].ToString();

  5. dan

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

  6. Jim

    Well, whether this misnamed or not, it certainly helped me – thank you.

Leave a comment

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

*