Posts tagged "JavaScript"

Inject route urls into JavaScript files in ASP.NET MVC

30 January 2012 at 22:27

The quest for unobtrusive JavaScript, in the limited sense of removing it from html, is often scuppered in ASP.NET MVC by the need to manipulate JavaScript in the framework, for example when adding a url to an ajax post by using Url.Action. This has often bugged me. I usually reluctantly create JavaScript variables to hold the url in the js file and set them in the view.

I recently came across this post by Khalid Abuhakmeh which posits an interesting solution revolving around using a view to emit the JavaScript file. I’m still not sure if I’m 100% happy with this as an approach for two reasons. Firstly it introduces a second location to your JavaScript resources which may not be immediately obvious to others using your code. Secondly, you have to do a few things to get the IDE to think the JavaScript is JavaScript whilst making sure it will be seen as a js resource by browser.

How can you get this view? First create a controller named JavascriptController, and add the following action:

public ViewResult Index(string file)

{

Response.ContentType = "text/javascript";

return View(file);

}

Here we set the response’s ContentType to JavaScript so browsers know they’re looking at JavaScript, then return a view based on the file argument.

Next create a folder in your Views folder or wherever is appropriate for your solution and name it Javascript. Create a view and name it as you would name your JavaScript file but without the .js extension, cart.cshtml for instance. Add your JavaScript, of course now with some added C# view love. Now add a new route like so:

routes.MapRoute(
"Javascript",
"js/{file}",
new { controller = "Javascript", action = "Index"});

Then reference the JavaScript in your pages:

<script src="js/cart" type="text/javascript"></script>

To get the IDE to interpret the js as js, in the view I add //<script type="text/javascript"> at the top and //</script> to the bottom. The JavaScript comments mean browsers ignore these tags. Similarly you can add //<script src="~/scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script> if you want VS IntelliSense, or add the usual if statement.

Hopefully the Microsoft bods will integrate a much better solution into VS soon. Perhaps you know of a superior approach?