How can I include css files from an MVC partial control?

后端 未结 9 1542
南笙
南笙 2020-12-28 09:15

I\'m using ASP.NET MVC and I have a partial control that needs a particular CSS & JS file included. Is there a way to make the parent page render the script

相关标签:
9条回答
  • 2020-12-28 09:32

    Before the render partial line, call @import as follows:

    <style type="text/css>
        @import url(cssPath.css);
    </style>
    

    Hope this helps.


    Just came across this option on Haacked and remembered your question. Use the header's Content placeholder on the partial view and just add the CSS to that form normally.

    0 讨论(0)
  • 2020-12-28 09:33

    Depending on how much CSS / JS your control needs, the safest route may be just to include the extra styling in your main CSS files. Saves an extra trip to the server, and it should all be cached by the client. I know this kills the self-containedness (to coin a phrase) of the control, but it may be your best bet.

    0 讨论(0)
  • 2020-12-28 09:38

    http://www.codeproject.com/Articles/38542/Include-Stylesheets-and-Scripts-From-A-WebControl-.aspx

    This article contains information about overriding HttpContext.Response.Filter which worked great for me.

    0 讨论(0)
  • 2020-12-28 09:38

    Todd's answer works fine, provided you have only one instance of the control and there's no other code that wants to "inject" anything in the tag for the master page. Unfortunately, you can rarely rely on this.

    I would suggest you include the all the css files you need in the master page. There will be a small perf hit on the first visit, but after that the browser caching will kick in. You can (and should) split your styles in multiple .css files to benefit from HTTP agents that can downoad them concurently. As for the .js files, I'd suggest to implement something close to the google.load() mechanism, that would allow you to load scripts on demand.

    0 讨论(0)
  • 2020-12-28 09:39

    Sorry, you cannot from a partial control refer "up" to something in the parent page (or add anything). The only communication is "down" from the parent to the partial by passing the ViewData / Model.

    You are describing functionality of a master page and a normal page using the content place holders, but partial controls do not function like that.

    But, if I am not mistaken, you can just physically add the script or link tags to the actual parent page that you render the partial page on - the CSS should be used by the partial page as well.

    0 讨论(0)
  • 2020-12-28 09:41

    If you willing to break conformance, you can just emit a style definition with the partial content. This tends to work in most recent browsers.

    0 讨论(0)
提交回复
热议问题