Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: OnServerClick event handler not called if using onclick

I have a peculiar problem here and I can't by my life figure out what the solution is. Note that the following code is not dynamically created, but just immediately in my aspx file.

<button type="button" runat="server" id="btnSubmit"
  OnServerClick="btnSubmit_Click" onclick="return confirm('Sure?');">
    Submit
</button>

This works just fine as long as I don't have the onclick attribute there, i.e. the OnServerClick handler is fired as it should. But when I use the onclick attribute it is not, no matter whether I confirm or decline the confirmation dialog box.

What am I doing wrong?

like image 507
Deniz Dogan Avatar asked Aug 07 '09 14:08

Deniz Dogan


3 Answers

If you look at the source code generated you will see the following:

onclick="return confirm('Sure?'); __doPostBack('btnSubmit','')"

so what is happening is the _doPostBack is never called. The hacky way to do what you're looking for is the following:

<button type="button" runat="server" id="btnSubmit"
  OnServerClick="btnSubmit_Click" onclick="if (confirm('Sure?')) ">

The real correct way would be to use a Web Control:

<asp:Button runat="server"
        OnClick="btnSubmit_Click" OnClientClick="return confirm('Sure?')" Text="Submit" />
like image 116
Yuriy Faktorovich Avatar answered Nov 14 '22 19:11

Yuriy Faktorovich


I had more success with

<asp:Button ID="btnSubmit" runat="server" Text="Save" UseSubmitBehaviour="false"
OnClick="btnSubmit_Click" OnClientClick="if (!confirm('Sure?')) return" />
like image 3
keith Avatar answered Nov 14 '22 18:11

keith


The accepted answer is not perfect. If you do not use type="button", the web page will do postback even you have clicked cancel. The correct and easiest way is to take advantage of short-circuit evaluation and do this hack: replace ; with && !, like below.

<button runat="server" id="btnSubmit"
        OnServerClick="btnSubmit_Click" onclick="return confirm('Sure?') && !">

The output will look like this:

<button id="btnSubmit"
        onclick="return confirm('Sure?') && ! __doPostBack('btnSubmit','')">

It gives correct return value because true && !undefined will return true and undefined will be evaluated and false && !undefined will return false and undefined will NOT be evaluated which is exactly what we want.

like image 3
Mygod Avatar answered Nov 14 '22 20:11

Mygod