Dynamic Bootstrap themes with ASP.NET using server-side bundling

I am setting up a system that needs to load the bootstrap theme that is being used from the web.config file (eventually, this might move to a database field for runtime changes).

Initially, I had my theme defined in the bundle.config file like so:

<?xml version="1.0" encoding="utf-8" ?> 
<bundles version="1.0"> 
    <styleBundle path="~/Content/css"> 
        <include path="~/Content/bootstrap.css" /> 
        <include path="~/Content/Site.css" /> 
        <include path="~/Content/bootstrap-theme.superhero.min.css" /> 

This worked well for statically defined theme, but I need to make it dynamic. It turns out that this was quite easy. Simply remove the theme from bundle.config and add it to BundleConfig.vb (or BundleConfig.cs for C# projects).

Before doing that, let’s go ahead and add it to the web.config file:

    <add key="theme" value="bootstrap-theme.superhero.min.css"/>

Then, we just add this one line to the bottom of the BundleConfig.vb file:

bundles.GetBundleFor("~/Content/css").Include("~/Content/" & ConfigurationManager.AppSettings("theme"))

It is important to notice that the virtual path for the bundle matches the same name as the path defined in your bundle.config file.

Now, whenever pages on your site are served, the theme css will be served along with the other bundled css. After testing, I’m pretty sure that the newly included css is last in line.

To change your theme, simply change it in web.config and reload. Or, replace the call to ConfigurationManager.AppSettings to a database call to retrieve the theme.

Also, make sure you’ve downloaded and saved the css theme to the Content folder before trying to access it.

You can get some nice free themes from Bootswatch.