Bundling in an ASP.Net MVC 4 project…

I recently came across a really good post on StackOverflow, but it seems to have been deleted, so I’m going to repost it for those of you who may need it.

My issue was such: I’m combining common JavaScript functionality in Pylons into a single file, and I wasn’t quite sure how to do this.  This is to save repeating the same functions in various views of my ASP.Net Web API based project.  (The project is built on the ASP.Net Web API, but has a web component as well, hence the need for web pages to make Ajax calls to the API).  Programmers are inherently lazy, and keeping multiple copies of the same function around is a bad idea from a maintenance perspective.  Just think, if you’ve got 10 copies of the same function, and you discover a bug, you’ve now got 10 things to update.  

To make it so that I’ve only got one copy of a function, I did the following:

  1. Created a new script file in the Scripts folder.  (In this case, I’ve called it “pylonCommon.js”)
  2. In the App_Start folder, in BundleConfig.cs, add a new bundle.  It’ll look something like the following:

    bundles.Add(new ScriptBundle(“~/bundles/pylonsCommon”).Include(

    “~/Scripts/pylonsCommon.js”));

  3. In _Layout.cshtml, you’ll now need to pull in the bundle.  This is done with the following, placed near the top of the file (just below the other @Scripts.Render statements:


@Scripts.Render(“~/bundles/pylonsCommon”)


And with that, you should be good to go!  You should now be able to call whatever JavaScript functions are in the pylonsCommon.js file.  

That being said, to enable bundling and minification, you’ll need to follow the steps listed here: http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s