skip to Main Content

I have landed on this bit of code to call a javascript function from c# successfully, but I can only seem to use it once per c# method. How can I call more than one function in a method? I’m sort of new to C#.

protected void btnAdd_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "firstEvent(event)", true);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "secondEvent(event)", true);
}

2

Answers


  1. I got into a similar issue when working with Blazor Webassembly. The solution i used was awaiting every call.

    If the script manager doesn’t allow awaiting them directly, try:

    protected async void btnAdd_Click(object sender, EventArgs e)
    {
        await Task.Run(() => ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "firstEvent(event)", true));
        await Task.Run(() => ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "secondEvent(event)", true));
    }
    

    It could happen because the script manager can’t support multiple calls at once, so it might be ignoring the 2nd call. At least, this is what happened to me.

    Login or Signup to reply.
  2. Ok, so your problem is two fold.

    Remember, all that command does is add some script to the web page, sends it down to client side.

    So, there are two ways to do this. Simple put both function calls into one, like this:

    ScriptManager.RegisterStartupScript(This.Page, Page.GetType,
      "text", "test1();test2();", True)
    

    And you can also do this:

    ScriptManager.RegisterStartupScript(This.Page, Page.GetType, "text", "test1();", True)
    ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "text2", "test2();", True)
    

    Note how we give a new "key" name – if you don’t do this, then the 2nd one is overwriting the next one.

    However, EVEN this will NOT work:

        ScriptManager.RegisterStartupScript(this.Page, Page.GetType, "text", "test1()", True)
        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "text2", "test2()", True)
    

    note the missing ";" after the function

    so

     Test1()   - only works for one
     Test1();  - will work if you add more
    

    So, if you eave out the trailing ";", then the script gets injected as

    Test1()Test2()
    

    And you need

    Test1();Test2();
    

    So, either put both calls in the one script inject like

    Test1();Test2();
    

    Or with your two script inject calls?

    Then you NEED both a different key name, and ALSO must add the trailing ";" so that they are seen as separate js function calls.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search