Tech Junkie Blog: ASP.NET MVC 5 From Scratch : Adding BundleConfig

Saturday, June 18, 2016

ASP.NET MVC 5 From Scratch : Adding BundleConfig

In our previous blog we've added a _ViewStart.cshtml layout to our project, which is the default layout for our pages if no layout is specified for the page.  In this blog we will add BundleConfig for the JavaScript libraries which includes JQuery, and Bootstrap that we've added to our MvcApp project in the previous blogs.  A configuration bundle allows you to group files that belongs in the same libraries together so that they can called with just one line of code.  In this blog we will be creating configuration bundles for JQuery, and Bootstrap to the MvcApp project.

Step-By-Step Instructions:

1.  Right-click on the folder "App_Start", then select Add → New Item → Visual C# → Class, name the class BundleConfig.cs



























2.  Now the App_Start folder should look like the screenshot below










3.  Open the BundleConfig.cs file, then delete the existing using statements, and then add the following namespaces

using System.Web;
using System.Web.Optimization;

4. The resulting code should look like the following up to this point
using System.Web;
using System.Web.Optimization;

namespace MvcApp.App_Start
{
    public class BundleConfig
    {
    }
}

5. If you see the System.Web.Optimization with the red underline, that means you have the reference to your project













6.  To add the reference open the NuGet Package Manager Console by selecting Tools → NuGet Package Manager →  Package Manager Console


7.  Once the Package Manager Console has been opened type in the following command Install-Package Microsoft.AspNet.Web.Optimization, then press "Enter"













8.  Once the package has been add you should get the following message "Successfully added 'Microsoft.AspNet.Web.Optimization 1.1.3' to MvcApp."

10.  Now the red underline is gone from the BundleConfig.cs file
















11. Inside the BundleConfig class add a static method call RegisterBundles with a BundleCollection call bundles parameter.  So the code should look like the following

using System.Web;
using System.Web.Optimization;

namespace MvcApp.App_Start
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
        }
    }
}

The code above tells MVC to register the bundles in the static method RegisterBundles

12. First lets create a bundle for the JQuery library by adding the following lines of code to the RegisterBundles method
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

The code above tells MVC to include all the files in the "Scripts" folder that has the string "jquery" in the file followed by a "-" and version number with the file extension ".js". Also give it the reference of "~/bundles/jquery", this is how we are going to reference the bundle in our views later on.

13. Now we are going to add the add the Boostrap library to the project in a similar fashion.
            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css"));

The code above tells MVC to reference the bootstrap script bundle as "~/bundles/bootstrap" and the include the files "bootstrap.js" and "respond.js" in the "Scripts" folder. Likewise reference the css files for bootstrap as "~/Content/css" and include the files "bootstrap.css" and "site.css" in the "Content" folder. The css bundle is a catch all bundle where all the css files in the first level of the Content folder will be referenced.

The final code for the BundleConfig class should look like this

using System.Web;
using System.Web.Optimization;

namespace MvcApp.App_Start
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js"));

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

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css"));
        }
    }
}

14. Now it's time to add the bundle configurations to our _Layout.csthml view.

15.  Open the _Layout.cshtml file under Views → Shared folder

16.  First we will add the css bundle, by typing in the following code in the head section
 @Styles.Render("~/Content/css")

17. Now scroll to the bottom of the page and add the JavaScript bundles to the layout page
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

The completed layout code should look like the following
<!DOCTYPE html>
<html>
    <head>
        <title>@Page.Title</title>
        @RenderSection("head", required: false)
        @Styles.Render("~/Content/css")
    </head>
    <body>
        <h1>This is from the _ViewStart.cshtml</h1>
        @RenderBody()
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
    </body>
</html>

If Visual Studio is complaining about the "@Scripts" and "@Styles" reference is missing then add the System.Web.Optimization to the Views web.config file.





















18.  Open the web.config file under the folder Views and add the following code
<add namespace="System.Web.Optimization">
</add>

Inside the <namespaces> tag
Here is how the web.config file should look like

  <system .web.webpages.razor="">
    <host factorytype="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <pages pagebasetype="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc">
        <add namespace="System.Web.Mvc.Ajax">
        <add namespace="System.Web.Mvc.Html">
        <add namespace="System.Web.Optimization">
        <add namespace="System.Web.Routing">
        <add namespace="WebApplication1">
      </add></add></add></add></add></add></namespaces>
    </pages>
  </host></system>

If you build the MvcApp project the missing reference error will disappear for the @Scripts and @Styles namespaces.

 19. Press Ctrl+F5 to run the application, you will get the following error message

Server Error in '/' Application.
Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

20.  To get rid of the error you have to open the web.config file under the application's root folder and delete the following lines

      
        <assemblyidentity culture="neutral" name="Newtonsoft.Json" publickeytoken="30ad4fe6b2a6aeed">
        <bindingredirect newversion="6.0.0.0" oldversion="0.0.0.0-6.0.0.0">
      </bindingredirect></assemblyidentity></dependentassembly>

21. Now open the NuGet Package Manager Console and type in the following update-package Newtonsoft.Json -reinstall, then press enter

22. When the package Newtonsoft.Json is reinstalled again you will get the following message "Successfully added 'Newtonsoft.Json 5.0.4' to MvcApp."

23.  There is one more thing that you have to do to make the bundle configs work, you have to register the bundles at the Application_Start() method in the Global.asax.cs file.

24. Open the Global.asax.cs add the following line at the end of the Application_Start() method

BundleConfig.RegisterBundles(BundleTable.Bundles);

Your Global.asax.cs file should look like the following at this point
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MvcApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


25. Now run the application again by pressing Ctrl + F5 and you should see the following
















26.  If you look at the source code you will see that JQuery and Bootstrap files have been added to the View that is displayed on the browser

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        
        <link href="/Content/bootstrap.css" rel="stylesheet"/>

    </head>
    <body>
        <h1>This is from the _ViewStart.cshtml</h1>
        

<h3>This is from Index.cshtml</h3>
        <script src="/Scripts/jquery-2.1.4.js"></script>

        <script src="/Scripts/bootstrap.js"></script>


15 comments:

  1. I had the error message BundleConfig does not exist in the current context" at step 24. I believe this is down to the App_Start on the end of the namespace in step 4, which wasn't there at the end of step 13.

    ReplyDelete
    Replies
    1. Took me awhile but that was my fix as well.

      Delete
    2. Thank you for catching the error I have made changes to the blog article so that other users won't have the same error.

      Delete
    3. AT point 18, THW TWO namespaces must be added also to the outer web.config file, else this won't work for me. VS 2013.

      Delete
    4. I had to close/open my Visual Studio after adding the web.optimization namespaces to the web.config files.

      Delete
  2. Walking thru this with VS2015, Fwk 4.6.1 and Empty MVC 4. Seeing a few variations to the instructions.

    1. In step #18 the resulting web.config is slightly different. In particular, the tags are not nested.















    2. In place of step 18, there also seems to be a new option. VS is indicating that you can add the following at the top of _Layout.cshtml.

    @using System.Web.Optimization

    This approach also requires an additional using statement in step 24.

    3. Steps 20-22 did not apply as the Package Manager Console indicated that Newtonsoft.Json 5.0.4 was installed along with Microsoft.AspNet.Web.Optimization.1.1.3.

    ReplyDelete
  3. Hi, tanks for the tutorial.
    But no, tou don't have removed said error.
    1) You must change everywhere in BundleConfig (also jpgs) the namespace MvcApp.App_Start to namespace MvcApp (removing App_Start from the end of it)
    2) to avoid error on BundleTable, that appears next, you must add:
    using System.Web.Optimization;
    inside Global.Asax.cs.

    ReplyDelete
  4. p.s. see also:
    https://www.stevefenton.co.uk/2013/02/the-name-bundleconfig-does-not-exist-in-the-current-context/

    ReplyDelete
  5. Hi, I use PHP Codeigniter, so this is my very first time with .net mvc. What will it happen if I dont use BundleConfig? I wrote all my references on the head of the html document as if I was doing it on PHP.

    ReplyDelete
    Replies
    1. Nothing will happen, a bundle config is just a way to bundle resources together, and selectively use it in views so that you don't have to include it on every page. If you put the scripts in the layout you will include it every page.

      Delete
  6. Thank You this was very nice and informative, great article indeed but doing step 18 and building did not fix @Styles and @Scripts issue on its own. But it instructed/allowed me to add @Using System.Web.Optimization at the top of _Layout.cshtml, which finally solved this for me, one way or other. What possibly caused this?

    ReplyDelete
  7. Took out respond.js line that was causing problems

    ReplyDelete