1
votes

Let's say I have a button which modifies some content inside an update panel:

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = "New Text";
}

I also want to execute some code on the client side, after the UpdatePanel has been updated. My first idea would be to execute ScriptManager.RegisterClientScriptBlock or RegisterStartupScript:

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = "New Text";

    var x = getSomeDatabaseQueryResultBasedOn(TextBox1.Text, ...);

    ScriptManager.RegisterStartupScript(this, typeof(WebForm1), "SomeKey",
        "/* this is my script, using `x` */", true)
}

However, the documentation of RegisterStartupScript says:

You use this method to register a startup script block that is included every time that an asynchronous postback occurs.

I don't want this code to execute "every time that an asynchronous postback occurs". I want it to execute only right now (after control is back with the browser). If Button2 is clicked, I don't want any script executed, and if Button1 is clicked again, x might be different and I want a new script to be executed. Unfortunately, I didn't find a ScriptManager.ExecuteOnce method.

Is there such a method? Or did I just misunderstand the documentation of RegisterStartupScript?

2

2 Answers

0
votes

The very next line from that documentation says:

"To register a script block for a control that is inside an UpdatePanel control so that script is registered only when the UpdatePanel control is updated, use the RegisterClientScriptBlock(Control, Type, String, String, Boolean) overload of this method."

Is that not what you want?

0
votes

When you include the StartupScript duing the async postback, it will only exist in the partial response sent from the server.

If you do something like this:

if(ScriptManager.IsInAsyncPostBack)
{
  myDiv.InnerText = "partial response";
  ScriptManager.RegisterStartupScript(Page, Page.GetType(), DateTime.Now.ToString("ssfff"), "alert(0);"), true);
}

Your response will look something like this:

|blabla|blabla|updatePanel_ctrl00|someparams
<div>partial response</div>
<script> alert(0); </script>

Thus that piece of javascript will execute as soon as the response is received.