How do I use jquery in asp.net mvc 4?

asp.net-mvc, jquery

Solution

There is no 'proper' way to do this in MVC, it is up to you entirely.

There are several common ways to do this.

You could place JQuery functions 'inline' within your views by placing them in `script` tags e.g.

<script>
    $('a').click(function() { alert("Click"); } );
</script>

However, this is not generally recommended, as it makes your JS harder to manage and re-use and bloats your HTML. You'd probably only do this if you had a real small piece of script, and didn't feel it was worth creating a new file for.

Alternatively, you could place your html in separate js files, and include reference to these in your views e.g.

`<script src="~/Scripts/mycusomtjquery.js"></script>`

This is better, as it does allow re-use and doesn't bloat your HTML, plus the browser is able to cache it.

An even better option is to take advantage of the Bundling feature in MVC 4 and use this. Place your js in a seperate file, register it as a bundle, and render this in your view

e.g.

Create you js in seperates files and place your custom code in there.

Place this in App_Start\BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/mycustomjquery")
                    .Include("~/Scripts/mycustomjquery.js")
                    .Include("~/Scripts/myothercustomjquery.js"));

Add a call to render the bundle in your view

@Scripts.Render("~/bundles/mycustomjquery")

This will render your js in a minfied and merged manner that can be cached by the broswer.

You can configure this to suit. Choose how to bundle up your js files, how many actual js files to make, where to render them etc.

Problem

I'm working on a site using ASP.Net 4 with MVC. I'm very familiar with WebForms & javascript, and have used jquery, but the bundling is confusing me. From what I can tell, all the javascript files are wrapped up in BundleConfig.cs, and downloaded with the header in the site.master file. So, I should just be able to put my additional functions and jquery calls in new tags. But it's obvious that the way jquery functions are supposed to go into the files are completely different than what I'm used to, and I can't get anything to operate, at all. Are there any short tutorials that can show me the proper way to do this in MVC? And not Razor, I don't need two learning curves here.

Original source