How to add javascript file by c# code in asp.net page.

After couple of hour searching over net get frustrated for none of working solutions.At end I found another method for adding java script js file in asp.net page.  Below I have given code for that. In This post I will give you two method for this.

Method 1:

Content in my js file is:


function GetFeed() {
alert("Hi Nishant");
}

Add js file into asp.net page during page_load time.

Method 1:


protected void Page_Load(object sender, EventArgs e)
{

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

}

Content In aspx page:


<input id="Button1" type="button" onclick = "GetFeed()" value="button" />

And It works fine.

Another Simple method:

Method 2:

LiteralControl javascriptRef = new LiteralControl("<script src='/Scripts/UpdateFeesContent.js'  type='text/javascript'>  </script>");
Page.Header.Controls.Add(javascriptRef);

Reference from: Here

Page Keyword: Add JavaScript file by code, Add JavaScript programatically by c#, Programatically add java script file in asp.net page.

Advertisements

2 thoughts on “How to add javascript file by c# code in asp.net page.

  1. Pingback: How to Parse JSON Date on client side by java script. | [Code Destination]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s