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
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.
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.
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.
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.
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.
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.