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.

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

<asp:literal /> is good, you can store the script in a text file and show it in the control > literal.text = io.file.readalltext(scripttextfilepath)
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.
1

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

1 Comment

This is the one I ended up using. Thank you! And thanks to everyone else too, I learn something from each post.
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.