ASP.NET MVC 4 - add a bundle from a controller?

I have several pages on my site that use certain CSS and JS resources, but they are the only page to use this css or js file. Therefore, I don’t want to include this CSS and JS link in every page. Instead of modifying each view to link to CSS / JS, I need it, I thought I could create a package in the controller and add it to the existing links, and then it will be included in the links to the bunch, but this does not seem to be possible, or maybe I'm just mistaken.

In my controller for the login page, for example, I thought I could write this:

Bundle styleBundle = new Bundle("~/bundles/registrationStyleBundle"); styleBundle.Include("~/Content/Themes/Default/registration.css"); BundleTable.Bundles.Add(styleBundle); 

And then I have this in my / Views / Shared / _Layout.cshtml:

 @foreach(Bundle b in BundleTable.Bundles) { if (b is StyleBundle) { <link href="@BundleTable.Bundles.ResolveBundleUrl(b.Path)" rel="stylesheet" type="text/css" /> } else if (b is ScriptBundle) { <script src="@BundleTable.Bundles.ResolveBundleUrl(b.Path)" type="text/javascript"></script> } } 

But this will not work - the only bundles that will appear on my page will be the ones that I specified in RegisterBundles (in / App_Start / BundleConfig.cs)

Any idea how to achieve such a "dynamic" or "runtime"?

EDIT . Following Jasen's advice, what I ended up with was to get the package creation / registration code from the controller and add it to RegisterBundles () in / App _Start / BundleConfig.cs. Thus, the package is already available, and the content becomes miniature. So:

 bundles.Add( new StyleBundle("~/bundles/registrationStyleBundle") .Include("~/Content/Themes/default/registration.css")); 

Then, in my opinion, I added the following:

 @section viewStyles{ <link href="@BundleTable.Bundles.ResolveBundleUrl("~/bundles/registrationStyleBundle")." rel="stylesheet" type="text/css" /> } 

Then, in / Views / Shared / _Layout.cshtml, I added the following:

 @RenderSection("viewStyles", required: false) 
+4
source share
1 answer

Use the @section Scripts { } block to conditionally add packages.

_Layout.cshtml

 <body> ... @RenderSection("Scripts", required: false) </body> 

Fooview.cshtml

 @section Scripts { @Scripts.Render("~/bundles/foo") } 

KungFooView.cshtml

 @section Scripts { @Scripts.Render("~/bundles/kungfoo") } 

In my BundleConfig, I usually group resources

 bundles.Add(new ScriptBundle("~/bundles/Areas/Admin/js").Include(...); bundles.Add(new StyleBundle("~/bundles/Areas/Admin/css").Include(...); bundles.Add(new ScriptBundle("~/bundles/Areas/Home/js").Include(...); bundles.Add(new StyleBundle("~/bundles/Areas/Home/css").Include(...); 

Now I can either define multiple layout files, or simply selectively add packages to the views.

+6
source

All Articles