Helping you solve those tough coding problems!

MVC: Accessing the RouteData inside of your C# code MVC: Accessing the RouteData inside of your C# code

Published on Feb 27, 2019 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. Enter the object ControllerContext.RouteData.




Using the ControllerContext.RouteData



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 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 | c# | mvc | routedata

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP