So how do we implement bundling in MVC?
Open BundleConfig.cs from the App_Start folder.
In BundleConfig.cs, add the JS files you want bundle into a single entity in to the bundles collection. In the below code we are combining all the javascript JS files which exist in the Scripts folder as a single unit in to the bundle collection.
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include( "~/Scripts/*.js"));
Below is how your BundleConfig.cs file will look like:
public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include( "~/Scripts/*.js")); BundleTable.EnableOptimizations = true; } }
Once you have combined your scripts into one single unit we then to include all the JS files into the view using the below code. The below code needs to be put in the ASPX or Razor view.
<%= Scripts.Render("~/Scripts/MyScripts") %>
If you now see your page requests you would see that script request is combined into one request.
How can you test bundling in debug mode?
If you are in a debug mode you need to set
EnableOptimizations
to true in the bundleconfig.cs file or else you will not see the bundling effect in the page requests.BundleTable.EnableOptimizations = true;
Explain minification and how to implement it
Minification reduces the size of script and CSS files by removing blank spaces , comments etc. For example below is a simple javascript code with comments.
// This is test var x = 0; x = x + 1; x = x * 2;
After implementing minification the JavaScript code looks like below. You can see how whitespaces and comments are removed to minimize file size, thus increasing performance.
var x=0;x=x+1;x=x*2;
How do we implement minification?
When you implement bundling, minification is implemented by itself. In other words the steps to implement bundling and minification are the same.
Explain Areas in MVC?
Areas help you to group functionalities in to independent modules thus making your project more organized. For example in the below MVC project we have four controller classes and as time passes by if more controller classes are added it will be difficult to manage. In bigger projects you will end up with 100’s of controller classes making life hell for maintenance.
If we can group controller classes in to logical section like “Invoicing” and “Accounting” that would make life easier and that’s what “Area” are meant to.
You can add an area by right clicking on the MVC solution and clicking on “Area” menu as shown in the below figure.
In the below image we have two “Areas” created “Account” and “Invoicing” and in that I have put the respective controllers. You can see how the project is looking more organized as compared to the previous state.
No comments:
Post a Comment