Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding Javascript File to User Control in .net

How do you add Javascript file programmatically to the user control?

I want the user control to be a complete package - ie I don't want to have to add javascript that's related to the user control on the page where it's used, when I can do it inside the control itself.

Since there is no Page object in the user control, how would you do it?

like image 827
sarsnake Avatar asked Feb 06 '09 18:02

sarsnake


2 Answers

In the Page_Load method of control.ascx.cs file:

LiteralControl jsResource = new LiteralControl();
jsResource.Text = "<script type=\"text/javascript\" src=\"js/mini-template-control.js\"></script>";
Page.Header.Controls.Add(jsResource);

HtmlLink stylesLink = new HtmlLink();
stylesLink.Attributes["rel"] = "stylesheet";
stylesLink.Attributes["type"] = "text/css";
stylesLink.Href = "css/mini-template-control.css";
Page.Header.Controls.Add(stylesLink);

This will load css and Javascript into the head tag of the main page, just make sure that the head has runat="server".

like image 123
sarsnake Avatar answered Oct 16 '22 15:10

sarsnake


You can register client script includes using the ClientScriptManager. Page is accessible through the Control.Page property.

Page.ClientScript.RegisterClientScriptInclude (
  typeof ( MyControl ), "includeme.js", "js/includeme.js"  );

EDIT: Sorry, for a total "complete package", its possible using scripts as Embedded Resources, and aquire dynamic URL's through the WebResource.axd handler. If this is not considered totally complete, then i guess it could be put in App_LocalResources, but it never gonna be just one file, unless the code and script is inline.

like image 39
baretta Avatar answered Oct 16 '22 15:10

baretta