Using jQuery with ASP.NET MVC 3

Using jQuery with ASP.NET MVC3 is pretty simple, especially now that it comes pre-installed with VS 2010. However, to set it up in a more scalable way with your project takes a little bit of work upfront but is definitely worth the extra effort in the long run.

1. Create a New Razor Helper

Let’s start by creating a new Razor helper in the App_Code folder (you may need to create this folder if it doesn’t already exist in your project). Add a new Razor view called Content.cshtml and replace the entire contents of that file with the following helper code:

@using System.Web.Mvc;

@helper Script(string scriptName, UrlHelper url) {

2. Add Script References to Layout Master

Add the following code to the end of _layout.cshtml (before the closing body tag).

@Content.Script("jquery-1.5.1.min.js", Url)
@Content.Script("jquery.unobtrusive-ajax.min.js", Url)
@RenderSection("scripts", false)

3. Adding New Script References

Adding any new script references is now easy. We can just add them to _layout.cshtml. Just be sure to add those references before the RenderSection line to ensure that the scripts load in the correct order.

@Content.Script("jquery-1.5.1.min.js", Url)
@Content.Script("jquery.unobtrusive-ajax.min.js", Url)
@Content.Script("jquery-ui-1.8.11.min.js", Url)
@Content.Script("modernizr-1.7.min.js", Url)
@RenderSection("scripts", false)

4. Adding Script References For Specific Pages

The RenderSection helper is used to call any page specific script references in the correct order i.e. after the main jQuery files have been loaded. The page specific script references can now be called in the same way i.e. simply add the required references to the relevant Razor view:

@section scripts {
    @Content.Script("jquery.validate.min.js", Url)
    @Content.Script("jquery.validate.unobtrusive.min.js", Url)

Voila! Now we’re ready to start having some fun with jQuery.

Omer Khan

Written by Omer Khan who lives and works in the beautiful Pacific Northwest. Follow him on Twitter