26 November 2010

Programmatically add JavaScript and CSS Stylesheet File to Asp.Net page?

Programmatically add CSS Stylesheet file to Asp.Net page

Sometimes its necessary to programmatically add some CSS stylesheets to your ASP.NET page, for example if you want to allow your users to change look and feel of your website by choosing themes etc.

Here is how to do it, just add this code to the Page_Init event handler on the Page where you want to insert CSS file:

    protected void Page_Init(object sender, EventArgs e)
    {

        HtmlLink css = new HtmlLink();
        css.Href = "css/fancyforms.css";
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["media"] = "all";
        Page.Header.Controls.Add(css);

    }

And thats it, next time you load this page, reference to your CSS file will be added at runtime to the page HTML code and loaded.
 
Programmatically add JavaScript File to Asp.Net page
 
If you do not want to add your JavaScript files declaratively via HTML to your ASP.Net page, you can do it in code, and here is how:

Just add this code to the Page_Init event handler on your page:

    protected void Page_Init(object sender, EventArgs e)
    {

        HtmlGenericControl js = new HtmlGenericControl("script");
        js.Attributes["type"] = "text/javascript";
        js.Attributes["src"] = "jscript/formfunctions.js";
        Page.Header.Controls.Add(js);

    }
 


No comments:

Post a Comment