0

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.

cchampion
  • 7,607
  • 11
  • 41
  • 51
  • Response.Write or any of the ASP.NET shortcuts. http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-%283c25242c-3c253d2c-3c252c-3c252c-etc%29.aspx If it needs to be the first script in the page... make sure its your first output statement. – Mike Furlender May 06 '14 at 01:13
  • Found similar question http://stackoverflow.com/questions/6928420/how-to-add-script-in-the-page-head-head-dynamically Given example is using custom Extension method for Page.Header: http://weblogs.asp.net/johnkatsiotis/archive/2008/08/08/add-scripts-to-head-dynamically.aspx – Shawinder Sekhon May 06 '14 at 12:31

3 Answers3

2

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.

Avitus
  • 15,640
  • 6
  • 43
  • 53
  • 1
    is good, you can store the script in a text file and show it in the control > literal.text = io.file.readalltext(scripttextfilepath) – Nitin May 06 '14 at 01:22
  • Is there a way to access that literal across different pages? I need to put the Literal in the master page and then only in certain other pages set the text on the literal. I tried this using the default asp.net project in VS2010 and I cannot access the literal's id in Default.aspx.cs. – cchampion May 06 '14 at 17:26
1

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

bytedreamer
  • 142
  • 8
  • This is the one I ended up using. Thank you! And thanks to everyone else too, I learn something from each post. – cchampion May 08 '14 at 02:18
1
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);
}
Rachit Patel
  • 854
  • 5
  • 12