How to add javascript file and css stylesheet dynamically to the header of the page in asp.net using c#?

In this tutorial you will learn how to add the javascript files and css stylesheets dynamically to the header of asp.net page inheriting masterpage using c#. Let's Suppose you have added a new module in your website inside a new folder, the folder name is NewModule. This module has its own css stylesheet and javascript files that will be attached to the more than 100 aspx webpages in it.

Now we have to add the javascript file and stylesheet to all these webpages of NewModule Dynamically. It’s not better approach to add these javascript file and css stylesheet to the masterpage and when these webpages of NewModule will be rendered then these javascript files and stylesheet will be automatically attached to the webpages located inside the NewModule folder. The reason why this approach is not good because the javascript file and stylesheet will be automatically attached to all those webpages other than NewModule folder that inherits from masterpage.

So let’s have a look example below that will cover the scenario that i discuss above.

How to add javascript file and css stylesheet dynamically to the header of the page in asp.net using c#?

Yourmasterpage.master.cs
protected override void OnPreRender(EventArgs e)
{
if (Request.RawUrl.ToLower().Contains("/newmodule /"))
{
LinkCss(); //It will Add CSS to Header
LinkJs(); //It will Add javascript to header
}
base.OnPreRender(e);
}
protected void LinkJs()
{
HtmlHead head = (HtmlHead)Page.Header;
HtmlGenericControl js = new HtmlGenericControl("script");
js.Attributes.Add("type", "text/javascript");
js.Attributes.Add("language", "javascript");
js.Attributes.Add("src", Page.ResolveUrl("~/js/yourjsfile.js"));
head.Controls.Add(js);
}
protected void LinkCss()
{
HtmlHead head = (HtmlHead)Page.Header;
HtmlLink css = new HtmlLink();
css.Attributes.Add("href", Page.ResolveUrl("~/styles/yourstylesheet.css"));
css.Attributes.Add("type","text/css");
css.Attributes.Add("rel","stylesheet");
head.Controls.Add(css);
}

Now let’s understand the code.

First of all in OnPreRender(EventArgs e) event of masterpage, I am checking whether the url in the address bar contains the NewModule flder name(the folder containing all the new developed webpages in which I want to add the javascript and stylesheet dynamically) using Request.RawUrl, if it contains the NewModule folder name then the LinkCss() and LinkJs() functions will get call and javascript file and css stylesheet will be attached to the aspx webpages dynamically. You can call LinkJs() and LinkCss functions in the page_load() function of your masterpage too.

So that's it. I hope you will find this tutorial very informative.

I love your feedback.

0 comments: