Tuesday, June 23, 2015

MVC4 Uncaught ReferenceError: $ is not defined

"Uncaught ReferenceError: $ is not defined"

This is a typical newbie error, specially when starting an ASP.NET MVC project. What's really going on is that the browser can't find the jquery file. But since  ASP.NET MVC automatically includes the javascript files as Script Bundles via the @Scripts.Render("~/bundles/"), we don't know why the jquery script file is not included even though it is present under References. 

Script.Render method basically allows automatic minification (compression) of javascripts and the Visual Studio IDE automatically adds some default bundles and placeholders for an ASP.NET MVC project.It's all nice and good but the problem is that the way ASP.NET MVC project is initially created, it makes it look like the references have already been added. The other equally confusing thing is the place ASP.NET MVC adds those script references by default. Unlike an ASP.NET Webforms application, the actual names of the javascript files don't appear in the aspx or cshtml files. So, they can't be found in the _Layout.cshtml or any other MVC *html file that is around.

So, what do we do? We go to the BundleConfig.cs file in the App_Start folder. Over there there is a method (that has already been created by the ASP.NET MVC project) that contains all of the references to the actual javascript files.

The javascript registration code in BundleConfig.cs file will look something like this -

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

Now the {version} part in the problematic part there. It doesn't seem to always work. Before I knew better, I thought it was a placeholder for us developers to fill in. But since the Visual Studio IDE doesn't give any indication how this can be fixed or even that something is wrong, a new developer trying to figure things out will never know what's going on.

But fear not, the fix is simple. Simply change the file name to the actual jquery file name. It's not the ideal solution but will work in a pinch -

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

And add the following to your _Layout.cshtml - @Scripts.Render("~/bundles/jquery")

And you are good to go! That's it. Now the script reference will show up in your browser as - src="/Scripts/jquery-2.8.2.js"

Another Victory! Now go have a beer!

No comments:

Post a Comment