Webistrate - Draw Your Own Conclusions

MVC 3: Accessing the RouteData inside of your code

Posted by Jamie Munro | December 5, 2011 | Tags:

Share

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.

Solution:

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.

Summary

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.

Share


Related Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books