Thursday, March 27, 2014

How to change or add script tag source from C#?

Here is how we can add script to page header from code behind in c#. The reason why I am doing this is I have these JavaScript files included in master page. And when I try to give path of these files I am getting issues with absolute page when I got to other pages since I have these in master page.

and one more reason why I did is I don’t want to change this every time if deploy to different environment from QA, Stage and Production.

This is how we can do it in your master page.

string js1 = HttpContext.Current.Request.ApplicationPath + "/Scripts/jquery.cycle2.js";
string js2 = HttpContext.Current.Request.ApplicationPath + "/Scripts/jquery.countdown.js";

Literal js1script = new Literal();
js1script.Text = string.Format(
@"<script src=""{0}"" type=""text/javascript""></script>", js1);
Page.Header.Controls.Add(js1script);

Literal js2script = new Literal();
js2script.Text = string.Format(
@"<script src=""{0}"" type=""text/javascript""></script>", js2);
Page.Header.Controls.Add(js2script);

Hope this is useful!!

No comments:

Post a Comment