cchampion
cchampion

Reputation: 7921

How to programmatically insert a javascript into a web page?

I am using ASP.NET and C#. Essentially I want to build a string like this using C#:

string strScript = "<script type="text/javascript">stuff</script>";

Then I want to insert that as the very first javascript in the web page (note that it is important that it be the first script in the page).

Thanks in advance for the help!

EDIT: sorry for the newb question(s) ... I'm on a time crunch and my javascript/asp.net skills are practically null.

Upvotes: 0

Views: 305

Answers (3)

Rachit Patel
Rachit Patel

Reputation: 862

protected void Page_Load(object sender, System.EventArgs e)
{
    myScript = "\n<script type=\"text/javascript\" language=\"Javascript\"   id=\"EventScriptBlock\">\n";
    myScript += "alert('hi');";
    myScript += "\n\n </script>";
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, true);
}

Upvotes: 1

bytedreamer
bytedreamer

Reputation: 142

I've successfully used the ClientScriptManager.RegisterClientScriptBlock method in previous projects.

Upvotes: 1

Avitus
Avitus

Reputation: 15958

You can just put an <asp:literal> on the top of the page and then set the text of that literal to be your javascript string on page load in the server side of things.

Upvotes: 2

Related Questions