如何从C#后台代码多次调用带不同参数的JavaScript函数?
Hey there! Let's break down what's happening with your current code and how to fix it so all your test() function calls run as expected.
The Problem With Your Current Code
Right now, you're using the same key "testFunction" every time you call RegisterStartupScript inside the loop. ASP.NET treats scripts with the same key as duplicates, so each new script you register overwrites the previous one. By the time the loop finishes, only the last script (test(9,10)) will be sent to the client and executed.
Solution 1: Use Unique Keys for Each Script
If you want to keep each test() call as a separate script, generate a unique key for each iteration by appending the loop index. This way, every script gets registered without being overwritten:
protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { // Add a semicolon to ensure valid JavaScript syntax string script = string.Format("test({0},{1});", i, i + 1); // Use a unique key by including the loop index this.Page.ClientScript.RegisterStartupScript(this.GetType(), $"testFunction_{i}", script, true); } }
Solution 2: Merge All Calls Into a Single Script (Recommended)
A cleaner, more efficient approach is to build one single script string with all your test() calls, then register it once. This reduces the number of script blocks sent to the client and avoids duplicate key issues entirely:
using System.Text; // Don't forget to include this for StringBuilder protected void Button1_Click(object sender, EventArgs e) { StringBuilder scriptBuilder = new StringBuilder(); for (int i = 0; i < 10; i++) { scriptBuilder.AppendFormat("test({0},{1});", i, i + 1); } this.Page.ClientScript.RegisterStartupScript(this.GetType(), "testFunction", scriptBuilder.ToString(), true); }
Quick Note
Make sure your JavaScript test() function is defined in the page (either in a <script> tag or external file) so the client can execute these calls without errors.
内容的提问来源于stack exchange,提问作者Ram

