powered by Slim Framework
enhanced by Nesbot.com

MVC 3: Accessing the RouteData inside of your code

Published on Dec 5, 2011 by Jamie Munro

You want to perform some dynamic processing in your code and you need to determine either the name of the current controller or the current action or both.


The ControllerContext.RouteData to the request!  Inside of your code you can use the following syntax to access the controller or action:

var controller = ControllerContext.RouteData.Values["controller"];
var action = ControllerContext.RouteData.Values["action"];

If you are inside of another class, you might need to access it via the current request, e.g.

var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
var action = HttpContext.Current.Request.RequestContext.RouteData.Values["action"];

Because the Values is a dictionary of key/value pairs you could easily use a for/each loop to iterate through them as follows:

foreach (KeyValuePair<string, object> kvp in ControllerContext.RouteData.Values)
string key = kvp.Key;
object value = kvp.Value;

You might notice that the value of the Value field is an object.  This is because it cannot be strongly typed as integers or strings or even json can be passed in through the URL.  Use caution when iterating over the variables because this could lead to a security breach.


When you need to access any data from the URL, the ControllerContext.RouteData provides access to the raw data after the router has executed and mapped the request allowing you to access the current controller and action as well as any of the URL variables.

Tags: ASP.NET | mvc3

<- MVC 3: Posting form variables that are not strongly typed  Home jQuery: Global AJAX Events for Start, Stop, Complete, or Error -> 
blog comments powered by Disqus