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”
Good post. How do you get the current area name? Nick
[…] I found that here. […]
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”);
thx
Cntrl= ViewContext.RouteData.Values[“controller”].ToString();
Action = ViewContext.RouteData.Values[“action”].ToString();
The title of this is incorrect, it does not get the current controller and action, it gets their names.
Well, whether this misnamed or not, it certainly helped me – thank you.
Helpful! Thanks!
Nice post, It was really helpful.
Thanks