5

I wish if i could change registered bundle collection items (JS or CSS files) dynamically after my MVC website published for example by hitting a button. Is it possible and what should we do to achieve this?

any help appreciated.

Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
QMaster
  • 3,743
  • 3
  • 43
  • 56

1 Answers1

4

After some search and try i found a way. I put this snippet in Session_Start but you can use it any where for example in button submit handler. I search for Bundle with a special name, then remove and create a new bundle with that name that i used in my project. (I did it to have new fresh bundle because i can't find any method to remove files from existing bundle and i appreciate if anyone knows how to do) Finally add files to bundle with include method of bundle and add bundle to BundleTable. (You could use IncludeDirectory method too)

Bundle bndl = BundleTable.Bundles.GetBundleFor("~/Content/css");
            if (bndl != null)
            {
                BundleTable.Bundles.Remove(bndl);
            }

            Bundle bndl2 = new Bundle("~/Content/css");
            bndl2.Include("~/Content/site.css", "~/Content/secondStyles.css", ... );
            BundleTable.Bundles.Add(bndl2);

At the last it's useful to read this article for working with bundles. Asp.net MVC 4 performance optimization with bundling and minification

Additional answers appreciated. Good Luck.

QMaster
  • 3,743
  • 3
  • 43
  • 56
  • 1
    Just a point to be wary of: because the bundle is cached, making changes to the BundleTable won't immediately change the served bundle. See: http://stackoverflow.com/a/12324888/792525 – decates Nov 04 '14 at 16:15
  • @decates Good point. I read it and I must do some tests. After test and research I'll share results. Thanks again for your heeds. – QMaster Nov 05 '14 at 10:31