Add JavaScript And CSS File To Page Header Dynamically


Today I got a scenario where I was supposed to add some custom JS and CSS file to the aspx page header from the code behind dynamically.

And in this article I will share how to achieve this in c#.


Adding JS and CSS files to Page Header in C#

In order to manipulate the HTML Controls in C#, Microsoft has provided a library for this with the namespace;
 using System.Web.UI.HtmlControls;
This namespace will let you manipulate all the html controls in the web page. And here we will add some custom JS and CSS files to the header of the page.

Below code will add a Javascript file to the page header that is located in Scripts folder of your project.
  HtmlGenericControl js = new HtmlGenericControl("script");
  js.Attributes["type"] = "text/javascript";
  js.Attributes["src"] = "Scripts/LoadedFromCodeBehind.js";

HtmlGenericControl is the generic class available to add or manipulate the html controls.

Below code will add a stylesheet to the page header that is located in the Styles folder of your project.
  HtmlLink css = new HtmlLink();
  css.Href = "Styles/AddedFromCodeBehind.css";
  css.Attributes["rel"] = "stylesheet";
  css.Attributes["type"] = "text/css";
  css.Attributes["media"] = "all";
HtmlLink is the class that is available to acheive this.
You can download the sample code from the above to test it at your end.

Happy Coding...

No comments:

Post a Comment