StyleBundle in ASP.NET MVC

In the previous tutorials, we learnt about bundling, and we also described how to bundle JavaScript files in an ASP.NET application. In this tutorial, we will learn how to bundle style sheets, that is CSS files.

The StyleBundle class of the ASP.NET does the CSS minification and bundling. This StyleBundle was derived from a Bundle class so it supports most methods as the ScriptBundle class.

As seen in the previous tutorial, we saw that the BundleConfig.cs file is located at App_Start\BundleConfig.cs file in the MVC folders. The BundleConfig.cs file is created by MVC framework by default. Our custom bundling code should be written in the BundleConfig.RegisterBundles() method as illustrated in the code snippet below.

Example: StyleBundle

public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new StyleBundle("~/bundles/css").Include(
        // ScriptBundles can be added here too..  

As you can see in the above example, we have created StyleBundle instance with bundle name as a virtual path. The bundle name must start with this "~/". We use Include() or IncludeDirectory() method to add the CSS files, passing the CSS file names as a string parameter.

Wildcards and CDN paths can also be used to bundle in style files, just like we did in the previous tutorial, where we discussed script bundling.

How to include Style Bundle in Razor View

To include a bundled stylesheet, we can use StyleBundle in the layout view and render bunch of CSS files in a single request. This has been made possible using static Styles class. Styles is a helper class to render CSS bundled files.

Example: Including Style Bundle in the View

<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @*your html codes goes here *@

As shown in the above example code snippet, we use Styles.Render() method to include a specified CSS bundle at runtime. We can quickly run this application to preview these changes.

Inviting useful, relevant, well-written and unique guest posts