M4N M4N - 1 year ago 84
ASP.NET (C#) Question

Why doesn't returning false from OnClientClick cancel the postback

I have a

where I use the
property to ask the user whether he really wants to perform an action, e.g:

function confirmDelete() {
return confirm('Do you really want to delete?');

<asp:LinkButton runat="server" OnClientClick="return confirmDelete()" ... />

This pattern usually works, but on this specific page, it doesn't. No matter whether I click OK or Cancel in the confirm dialog, the postback is executed.

Just for completeness (to answer pst's question): the rendered HTML is OK. E.g. it looks like this:

<a id="ctl00_c1_content_btnDelete" onclick="return confirmDelete();"
href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(..))"
... >

Answer Source

The reason for the behavior was another piece of javascript, where a handler for the link(button)'s click event was registered via jquery, e.g. something similar to this:

$(document).ready(function() {
  $('a').click(function() {
    // ...
    return (someCondition == true);

It seems this click-handler was called after the one registered by OnClientClick, and when this one returned true, then the postback occurred, independent of the result of the first click-handler (the confirm dialog).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download