Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC 4 - Add Bundle from Controller?
    primarykey
    data
    text
    <p>I have some pages on my site that use certain CSS and JS resources - but they are the only page(s) to use that css or js file - so I don't want to include that CSS and JS reference in every page. Rather than modify each View to reference the CSS/JS it needs, I thought I could create a bundle in the Controller and add it to the Bundles that are already registered, and then it would be included in the bundle references, but this does not appear to be possible, or maybe I'm just going about it the wrong way.</p> <p>In my Controller for a registration page for example, I thought I could write this:</p> <pre><code>Bundle styleBundle = new Bundle("~/bundles/registrationStyleBundle"); styleBundle.Include("~/Content/Themes/Default/registration.css"); BundleTable.Bundles.Add(styleBundle); </code></pre> <p>And then have this in my /Views/Shared/_Layout.cshtml:</p> <pre><code>@foreach(Bundle b in BundleTable.Bundles) { if (b is StyleBundle) { &lt;link href="@BundleTable.Bundles.ResolveBundleUrl(b.Path)" rel="stylesheet" type="text/css" /&gt; } else if (b is ScriptBundle) { &lt;script src="@BundleTable.Bundles.ResolveBundleUrl(b.Path)" type="text/javascript"&gt;&lt;/script&gt; } } </code></pre> <p>But this does not work - the only bundles to get rendered to my page end up being the ones I specified in <code>RegisterBundles</code> (in /App_Start/BundleConfig.cs)</p> <p>Any idea how to achieve this kind of "dynamic" or "runtime" bundling?</p> <p><strong>EDIT</strong>: Following Jasen's advice, what I ended up doing was taking the bundle creation/registration code out of the controller and adding it to RegisterBundles() in /App_Start/BundleConfig.cs. This way, the bundle is already available and the contents get minified. So:</p> <pre><code>bundles.Add( new StyleBundle("~/bundles/registrationStyleBundle") .Include("~/Content/Themes/default/registration.css")); </code></pre> <p>Then, in my view, I added this:</p> <pre><code>@section viewStyles{ &lt;link href="@BundleTable.Bundles.ResolveBundleUrl("~/bundles/registrationStyleBundle")." rel="stylesheet" type="text/css" /&gt; } </code></pre> <p>Then, in /Views/Shared/_Layout.cshtml, I added this:</p> <pre><code>@RenderSection("viewStyles", required: false) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload