Translating Controller, Action, and Route Data to a JavaScript Object in ASP.NET MVC 3

To enable a more rich JavaScript/Ajax experience on a web page, I had need of more detailed information regarding the route that resulted in the current View being displayed. I checked around a few sites, and nothing popped out as obviously awesome.

As I was putting the JavaScript in the Layout/Master page, I had few direct assumptions about the location of the View/route that was currently being executed.

Here are the two options I created this evening.

Option one is admittedly more limited, but it serves to demonstrate the basic technique:

<script type="text/javascript">
        
    var _servedFromUrl = "@Url.RouteUrl(this.ViewContext.RouteData.Values)";
    @{ 
        string action = ViewContext.RouteData.Values["action"].ToString();
        string controller = ViewContext.RouteData.Values["controller"].ToString();
    }
    var action = "@action";
    var controller = "@controller";
    
</script>

Note that the code above is contained within a <script> block, as the final destination goal is to make these values available within JavaScript in the browser.

Above, there are actually 2 different options. The first option, results in a string that could look something like this:

/Discussions/Edit/5522

It could be useful to someone. However, it wasn’t useful to me. The next step was to discretely retrieve the action and controller. As you can see, these result in two JavaScript variables, aptly named, action and controller.

var action = "Edit";
var controller = "Discussions";

In this case though, I wanted access to all the values, in a more natural JavaScript format: A JavaScript Object with named (ad-hoc) properties.

<script type="text/javascript">        
    var route = {
        @{                 
            string comma = "";
            foreach (var name in ViewContext.RouteData.Values.Keys)
            { 
                string val = ViewContext.RouteData.Values[name].ToString();
                @: @comma'@name': '@val'
                comma = ",";
            }    
        }                   
        };
</script>

The code above loops through all of the RouteData Keys, and adds each and the corresponding value to a JavaScript object instance named route.

The results:

<script type="text/javascript">
    var route = {             'id': '5522'
                 , 'action': 'Edit'
                 , 'controller': 'Discussion'
    };

</script>

Simple, with discrete values.