Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Am I injecting this correctly?

string myScriptName = "EventScriptBlock";
string myScript = string.Empty;

//Verify script isn't already registered
if (!ClientScript.IsClientScriptBlockRegistered(myScriptName))
{
    Response.Write('b');
    myScript = "
<script type="text/javascript" language="Javascript" id="EventScriptBlock">
";
    myScript += "alert('hi');";
    myScript += "

 </script>";

    ClientScript.RegisterClientScriptBlock(this.GetType(), myScriptName, myScript);
}

This is in my Page_Load, but I never see an alert and I have no JavaScript errors either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use registerstartupscript instead of registerclientscriptblock!

RegisterStartupScript When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM

RegisterClientScriptBlock When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error

Difference between registerstartupscript and registerclientscriptblock

protected void Page_Load(object sender, System.EventArgs e)
 {
      string myScript = "
<script type="text/javascript" language="Javascript" id="EventScriptBlock">
";
        myScript += "alert('hi');";
        myScript += "

 </script>";
     Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...