Prevent ASP.NET ImageButtons from submitting twice!(hockblogs.net)
submitted by
hockman(505) 3 years, 7 months ago
Hi there,
I'm currently rewriting some ASP.NET code, especially code that has to do with ASP.NET Buttons (and in my case: ASP.NET ImageButtons). The current situation allows users to click a lot of times on submit imagebuttons, which results in multiple submits and multiple calls to a webserver.
WE DON'T WANT THAT!!! Yell
In this article I don't want to go into the discussion that this should always be prevented by a developer (I agree with that!), but I still think there's a lot of code out there that still doesn't have this piece of functionality implemented. At least at my project it doesn't! Undecided. So we'll have to add an OnClientClick event to our ImageButton, preventing our users from submitting twice. After seeing Dave Ward's post, I thought that this was a simple solution:
<asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!" />
But then I immediately walked into problems. Since ASP.NET Imagebuttons don't have the UseSubmitBehaviour property like normal ASP.NET buttons do, we'll have to do the postback ourselves.
So thinking writing the following logic would make some sense:
<asp:ImageButton runat="server" ID="bevestigImageButton" ImageUrl="/images/discussie-bevestig.png" OnClick="bevestigImageButton_Click" OnClientClick="javascript: this.disabled = true;__doPostBack('bevestigImageButton','')" />
Since my page (actually it is an UserControl) has ASP.NET Validation Controls on it (RequiredFieldValidators), the ASP.NET Required Field Validators will fire, but still the ASP.NET ImageButton get's submitted. AAAARGGG Frown.
So by first checking if the Page was valid by making use of the Page_ClientValidate method, we can prevent the page from submitting. Once the page is valid, we disable the ImageButton that was clicked on and do a full PostBack to the server. This results in the following code, which works for me!
<asp:ImageButton runat="server" ID="bevestigImageButton" ImageUrl="/images/discussie-bevestig.png" OnClick="bevestigImageButton_Click" OnClientClick="javascript: Submit(this);" />
<script type="text/javascript" language="javascript">
function Submit(source){
Page_ClientValidate();
if (Page_IsValid){
source.disabled = true
__doPostBack(source.name, '');
}
return Page_IsValid;
}
</script
|category: ASP.NET
|Views: 31
tags:
ASP.NET another
Everyones tags:
Your Tags: