button firing click event twice

后端 未结 14 2065
忘了有多久
忘了有多久 2021-02-07 21:28

It seems that sometimes (but not always) my button click event is being fired twice. The fact that it seems to happen sometimes but not always is really puzzling me. Here is m

相关标签:
14条回答
  • 2021-02-07 21:54

    One possible reason:
    Check your button declaration in your .aspx source. If you have a 'runat=server' and onclick="button1_click", and you have an event handler in your code-behind (ie. .aspx.vb), it will cause the event to be fired twice. Here is an example in xxx.aspx:

    <asp:Button id="button1" onclick="button1_Click" runat="server" Text="Click Me!"></asp:Button>
    

    This declaration should be:

    <asp:Button id="button1" runat="server" Text="Click Me!"></asp:Button>
    

    Good luck!

    0 讨论(0)
  • 2021-02-07 21:55

    It is because the button type is submit. You need to change it to button to solved the button events triggering twice. Refer this blog for further explanation.

    https://mzulkamal.com/blog/asp-net-web-form-html-button-tag-fires-two-times-s

    0 讨论(0)
  • 2021-02-07 22:02

    The correct way (in the ASP.NET Web Form Page), as already pointed out by couple of other contributors, is to add the type="button" attribute to the element, and associate a onserverclick event delegate handler.

    For example:

    <button type="button" id="btnSave" runat="server" onserverclick="btnSave_ServerClick" class="btn btn-success btn-label">
        <i class="fa fa-save"></i>Save
    </button>
    

    Hope this helps.

    0 讨论(0)
  • 2021-02-07 22:02

    I had same issue, but quite different cause. I setup container panel defaultbutton property to the button firing twice. After removing the "DefaultButton" property from the Asp:Panel the problem is solved.

    0 讨论(0)
  • 2021-02-07 22:03

    The solution is already been mentioned in different answer . Use type ="button" instead of submit

    Here is a sample code

        <span class="input-group-btn">
          <button id="btnLoadCustomerFile" class="btn btn-default" type="button" runat="server" onserverclick="btnLoadCustomerFile_Click" >Load</button>
           </span>
    

    And the backend code to handle the on click

     protected void btnLoadCustomerFile_Click(object sender,EventArgs e)
        {
            LoadCustomerFile();
          }
    
    0 讨论(0)
  • 2021-02-07 22:04

    I just came across this same problem and wanted to point out that removing the "Handles btnSave.Click" from your event will prevent it from being called twice. For Example, use this in the code behind:

    Protected Sub btnSave_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
        'Do Something
    End Sub
    

    Instead of this:

    Protected Sub _btnSave_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        'Do Something
    End Sub
    
    0 讨论(0)
提交回复
热议问题