Tech Junkie Blog - Real World Tutorials, Happy Coding!: End-to-End ASP.NET MVC: Adding BundleConfig

Saturday, June 18, 2016

End-to-End ASP.NET MVC: 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 NorthwindCafe 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 NorthwindCafe 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 NorthwindCafe.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".  This will install all the dependencies as well.



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

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 NorthwindCafe.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 NorthwindCafe.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.3.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.Routing" />
        <add namespace="NorthwindCafe" />
        <add namespace="System.Web.Optimization"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

If you build the NorthwindCafe 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 NorthwindCafe."

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.Routing;
using System.Web.Optimization;
using NorthwindCafe.App_Start;

namespace NorthwindCafe
{
    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>
    
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h3>This is from Index.cshtml</h3>
</body>
</html>


    <script src="/Scripts/jquery-3.3.1.js"></script>

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

</body>
</html>

Similar Posts:

53 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
    5. I had to add

      using Panele.App_Start;

      to Global.asax.cs

      P.S: Panele is my solution name.

      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
  8. Thanks for the tutorial it really helped!

    ReplyDelete
  9. Are you looking for the Best OGX Shampoo for hair fall? throughout the internet? We know that a shiny and healthy hair is important to add up in your personality. Therefore, you must use the best quality shampoo that must be beneficial for your hair.

    ReplyDelete
  10. I like your blog.You have done Excellent work. I appreciate.Here I want to inform all of you if you are looking for to resolve your Norton Antivirus problems,so you are in right place.we always available for your support.So whenever you need any help so just click on this link- norton Antivirus ondersteuningsnummer

    ReplyDelete
  11. Excellent post. I certainly appreciate this website.Keep writing.well here if you want to Overcome the issues of Avast antivirus.Pick the Best Assistance over our site to resolve your queries.Visit us :avast antivirus ondersteuning

    ReplyDelete
  12. I am really enjoying your site.It’s simple, yet effective, thank you for this article.Now I have to share some information about How To Fix “mcafee Antivirus” problem. If you have any problem rearding Mcafee so click on this site:mcafee antivirus nummer belgie

    ReplyDelete
  13. I’m really impressed with your writing skills and also with the layout on your blog it's Very interesting to read.Now Here i would llike to share some information about HP Printer If you are facing any problem relate to your HP Printer's we wil resolve your queries at sam time.For any help please visit on our website:hp printer contact belgie

    ReplyDelete
  14. Next time I read a blog, Hopefully it does not fail me just as much as this one. After all, I know it was my choice to read, however I actually believed you would probably have something useful to talk about. All I hear is a bunch of complaining about something you could possibly fix if you weren't too busy searching for attention.disinfecting san antonio

    ReplyDelete
  15. Watch movies online sa-movie.com, watch new movies, series Netflix HD 4K, ดูหนังออนไลน์ watch free movies on your mobile phone, Tablet, watch movies on the web.

    SEE4K Watch movies, watch movies, free series, load without interruption, sharp images in HD FullHD 4k, all matters, ดูหนังใหม่ all tastes, see anywhere, anytime, on mobile phones, tablets, computers.

    GangManga read manga, read manga, read manga online for free, fast loading, clear images in HD quality, all titles, อ่านการ์ตูน anywhere, anytime, on mobile, tablet, computer.

    Watch live football live24th, watch football online, ผลบอลสด a link to watch live football, watch football for free.

    ReplyDelete
  16. Simply unadulterated brilliance from you here. I have never expected something not as much as this from you and 먹튀검증 have not confounded me by any reach out of the inventive vitality. I acknowledge you will keep the quality work going on.

    ReplyDelete
  17. I am overwhelmed by your post with such a nice topic. Usually I visit your 안전놀이터 and get updated through the information you include but today’s blog would be the most appreciable. Well done! Your information was very useful to me. That's exactly what I've been looking for 메이저토토사이트! What kind of article do you like?? If someone asks, they will say that they like the article related to 메이저사이트 just like your article. If you are interested in my writing, please visit !! What a nice comment!Nice to meet you. I live in a different country from you. Your writing will be of great help to me and to many other people living in our country. I was looking for a post like this, but I finally found 토토사이트.

    ReplyDelete
  18. What a post I've been looking for! I'm very happy to finally read this post. 바둑이사이트 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.

    ReplyDelete
  19. My curiosity was solved by looking at your writing. Your writing was helpful to me.카지노사이트I want to help you too.

    ReplyDelete
  20. I'm so happy to finally find a post with what I want. 토토커뮤니티 You have inspired me a lot. If you are satisfied, please visit my website and leave your feedback.

    ReplyDelete
  21. I'm writing on this topic these days, , but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts. 토토커뮤니티

    ReplyDelete
  22. This is one very interesting post. I like the way you write and I will bookmark your blog to my favorites.메이저놀이터

    ReplyDelete
  23. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts.먹튀검증커뮤니티

    ReplyDelete
  24. I found the answer I was looking for in your article. I'm going to quote your article and write it on a blog. 바카라사이트

    ReplyDelete
  25. ou need to be a part of a contest for one of the highest quality sites on the 토토사이트. I most certainly will recommend this site!

    ReplyDelete
  26. Thanks for sharing this.,
    Leanpitch provides online training in A-CSPO during this lockdown period everyone can use it wisely.
    Join Leanpitch 2 Days A-CSPO Certification Workshop in different cities.

    a-cspo certification
    a-cspo training

    ReplyDelete
  27. When I read an article on this topic, Bóng 88 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

    ReplyDelete
  28. That is really fascinating, You are an excessively professional blogger. I have joined your rss feed and stay up for searching for extra of your magnificent post. Also, I’ve shared your website in my social networks. ufabet168

    ReplyDelete
  29. When did it start? The day I started surfing the Internet to read articles related to . I've been fond of seeing various sites related to 먹튀검증 around the world for over 10 years. Among them, I saw your site writing articles related to and I am very satisfied.

    ReplyDelete
  30. It's the same topic, but I was surprised that it was so different from my opinion. I hope you feel the same after seeing the writings I have written. 토토사이트

    ReplyDelete
  31. I accidentally searched and visited your site. I still saw several posts during my visit, but the text was neat and readable. I will quote this post and post it on my blog. Would you like to visit my blog later? 메이저놀이터추천

    ReplyDelete
  32. Thank you for any other informative blog. Where else may just I am getting that kind of information written in such a perfect method? I have a mission that I’m simply now working on, and I have been on the glance out for such info. 안전놀이터추천

    ReplyDelete
  33. First of all, thank you for your post. Your posts are neatly organized with the information I want, so there are plenty of resources to reference. I bookmark this site and will find your posts frequently in the future. Thanks again ^^ 먹튀커뮤니티

    ReplyDelete
  34. I am very impressed with your writingsex I couldn't think of this, but it's amazing! I wrote several posts similar to this one, but please come and see!

    ReplyDelete
  35. I’m not sure exactly why but this weblog is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists. 안전놀이터순위

    ReplyDelete
  36. Hi ! I specialize in writing on these topics. My blog also has these types of articles and forums. Please visit once. 메이저놀이터

    ReplyDelete
  37. Hello, I am one of the most impressed people in your article. 메이저토토사이트 I'm very curious about how you write such a good article. Are you an expert on this subject? I think so. Thank you again for allowing me to read these posts, and have a nice day today. Thank you.

    ReplyDelete
  38. Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job! 메이저토토사이트 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.

    ReplyDelete
  39. Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information. 안전놀이터 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.

    ReplyDelete
  40. Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon 먹튀검증업체 I would like to write an article based on your article. When can I ask for a review?!

    ReplyDelete
  41. Thank you so much for such a well-written article. It’s full of insightful information. Your point of view is the best among many without fail.For certain, It is one of the best blogs in my opinion. 안전놀이터추천

    ReplyDelete
  42. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts. 스포츠토토사이트

    ReplyDelete
  43. What a post I've been looking for! I'm very happy to finally read this post. 토토커뮤니티 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.

    ReplyDelete

Search This Blog