I've got the following function (inside file.aspx.cs):
private void Alert(string message)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage", $"alert('{message}')", true);
}
When I call this function twice or more in a row, only the first alert will pop on the screen. E.g
protected void Button1_Click(object sender, EventArgs e)
{
// button1 on click event
Alert("First alert"); // this does show up on the screen
Alert("Second alert"); // this does not show up
}
Why is that?
CodePudding user response:
You need to give those script blocks different keys such as alertMessage1
and alertMessage2
. From Microsoft docs:
A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.
I don't recommend this kind of coding style though. I instead recommend using API endpoints and driving the UI using JavaScript rather than server-side C# code. This is VERY clunky. Every button press causes a whole page reload and server-side rendering, and then a script block gets inserted into the HTML code which makes caching impossible.