views:

187

answers:

1

How do I inject a script tag such as

<script src="somejsfile"></script>

or

<script type="text/javascript>some javascript</script>

into the head tag of a page from a partial view?

A: 

Partial views are UserControls. Can't you use RegisterClientScriptInclude method of ClientScriptManager?

protected override void OnLoad(EventArgs e) {
    base.OnLoad(e);
    Page.ClientScript.RegisterClientScriptInclude("some key", "http://website/javascript.js");
}
This applies to ASP.NET WebForms, but not MVC.
Chris Pietschmann
This will work in MVC when working off a view but it won't work in a partial view as there's now way to inherit a master page.
vakman
Your edit is definitely a web form approach and won't work in MVC.
vakman
MVC is built on top of ASP.NET, so `Page_Load` event and `Page.ClientScript` behave the same as in "Web Forms" app. I just tried it. Though `RegisterClientScriptInclude` puts the <script> where the user control is, not in the <head>.
Interesting. If it doesn't put it in the head though then I may as well just put the script tag directly in the view.
vakman
HTML 4.0 18.2.1 : "The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document." So yes, script in body is OK.