Search code examples
javascriptc#asp.netmethodscall

Call the same method of JS in C# asp.net


I want to call a Javascript method more than once in C#. I have this code.

for (int i = 0; i < numFa; i++)
{
    ClientScript.RegisterStartupScript(this.GetType(), 
        "addrow", "addRow('tblPets');", true);
}

The method adds a row in a table with id tblPets. So if numFa = 2 it adds only one Row instead of two.


Solution

  • According to MSDN link ClientScript.RegisterStartupScrip

    A startup 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.

    So there is only one issue with your code which is on every iteration you are registering same key (addrow).

    You can solve this issue by giving diffrent key-value on each iteration. Try below code

     for (int i = 0; i < numFa; i++)
            {
                ClientScript.RegisterStartupScript(this.GetType(),
                     string.Format("addrow{0}", numFa), "addRow('tblPets');", true);
            }
    

    Hope it will help.