ASP.NET Web form html button tag fires two times. - SOLVED

You might working with html bootstrap project and your front end coder give you html code with button elements. You browse on the net and found you can use button as a valid asp.net web form controller by adding runat="server" attribute. Yes it is true, by doing that you can set the event method by configure onserverclick attribute for your button elements. Yes it is true again. You can achieve this like sample code below. 

 
<button runat="server" id="button1" type="submit" onserverclick="method1" class="btn btn-primary" >Submit button</button>
 

Its working fine BUT somehow you found that when  the project go live, you encounter issue where many duplicate data occur. You start wondering why.?

Open visual studio, start debugging. The code just working fine. You have no idea why it is happen. 

Submit button behavior

The issue is because of the type is set to submit. So its mean that the button are meant to submit the form. As you notice that asp.net wrap all html with one form. So when you click on the button with type submit, the form will be submit to server. So why data is duplicate. If you notice whe you view source of the page. You can see this method of function.   
 
function __doPostBack(eventTarget, eventArgument) {

    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {

        theForm.__EVENTTARGET.value = eventTarget;

        theForm.__EVENTARGUMENT.value = eventArgument;

        theForm.submit();

    }
}
 

Capture.PNG

So to explain this, when user click on the button with type submit, its actually trigger 2 times first from the button type it self, second from onclick function which is resubmit back the form. 

Solution

To solve this, you need to change type button from submit to type button. Refer below. 
 
<button runat="server" id="button1" type="button" onserverclick="method1" class="btn btn-primary" >Submit button</button>
 

The above should solved button firing click twice issue. 

   

 

 

 Back to listing