Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my ASP.net function executing only once?

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?

like image 724
Nave Twizer Avatar asked Mar 27 '26 08:03

Nave Twizer


1 Answers

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.

like image 133
Sedat Kapanoglu Avatar answered Mar 28 '26 22:03

Sedat Kapanoglu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!