Trigger the bundle inclusion from partial or edito

2020-07-24 08:17发布

问题:

I'm building a framework on top of ASP.NET MVC 4. I like the new bundling feature in MVC4 but I'm running into an issue and I'm not sure if the new bundling features address this scenario.

My layout view is rendering it's script bundles at the bottom of the page before </body>.

Since my project is a framework, the view doesn't know all of the bundles that the page will need. My project is making heavy use of editor templates, which may need to include some javascript, but can't render it in the editor template itself because:

  • The script needs to be included only once and the editor template may be rendered more than once.
  • The script may depend on other javascript libraries like jQuery, which haven't been included yet (they are rendered at the bottom of the page).

So, what I'd like to do is something like this in an editor template:

@Scripts.TriggerInclusion("~/path/to/bundle/that/this/editor/needs")

And that would cause the bundle script tag to be rendered towards the end of the page only once.

I could go to the trouble of building this into my project's infrastructure, but I'm hoping that this sort of thing is already supported somehow. Thanks!

回答1:

This is something we are tracking in our backlog, its a fairly complex feature so we probably won't get to this for a few versions.

Our early thoughts are basically:

  • Allow registration of named assets, i.e. Assets.Register("jquery").Include("~/scripts/jquery.js")
  • Allow inclusion of assets by name in bundles
  • Add something like Scripts.Requres("jquery") which is similar to your TriggerInclusion, which basically registers the jquery asset on the page.
  • Something like Scripts.RenderRegistered() would render out all of the registered scripts on your page, in a location of your choosing, and also do deduplication of assets, etc.

We aren't sure how high to prioritize this feature, so if this is something that you really want, I created an issue on the codeplex site here, vote for it.



回答2:

I rolled my own. It was easy to build and works well for me.

https://github.com/ronnieoverby/MvcAssetManager/blob/master/MvcAssetManager/Infrastructure/AssetManager.cs

There's likely some bugs, I haven't used it so much because most of my projects are still MVC3. But what little I have used it, it's done the trick.