Lots of code that I have seen reference this:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Which is great, and it works...if "something" is included. Do I have to add a reference to get these? Use NuGet? Copy a DLL? Where does this come from?
When I run my project, I get a 404 for that resource.
You need to create the bundle. This is often done in the App_Start\BundleConfig.cs
file in your ASP.NET MVC 4 project. It is all explained in Bundling and Minification .
In the BundleConfig
class you need something like this (this method should execute in Application_Start
):
public static void RegisterBundles(BundleCollection bundles) {
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// ... more registrations ...
}
The javascript source files should exists in the Scripts
folder. The tutorial linked above explains how minified versions are bundled in the release build etc.
FYI - I have seen many examples of using Bundles in MVC, but most neglect to mention that the assemblies for this are in System.Web.Optimization.dll and you can get this from NuGet by adding the Microsoft ASP.NET Web Optimization Framework package.
Yes, you must register the bundles in your application.
Global.asax.cs :
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
// Register the bundles
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
BundleConfig.cs :
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.livequery.js",
"~/Scripts/jquery.numeric.js"
));
}
So when you put this code in your view :
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
It will render 4 javascript files.
More : Bundling and Minification
In your project App_Start/BundleConfig.cs
is the declaration for all bundles.
Consider this:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
In this case if you reference "~/bundles/jqueryval" it will include the 2 listed scripts for you, and as a bonus, it will minify them (if you run your project in "Release" mode).
Take a look at this for more details.
- Go to App_Start folder.
- Opoen BundleConfig.cs
- Inside the RegisterBundles method, check if you have the following.
bundles.Add(new ScriptBundle("~bundles/jqueryval").Include("~/Scripts/jquery.min.js"));
Please not that inside the Include method, it is including for the files in your project.