Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to intercept a Button postback

I've seen other solutions like this one which is pretty straightforward but what if the javascript function does more than just confirm('sure?');? I never know when it will return a bool.

So I've decided to implement all my ASP.NET Buttons like this:

<button id="btnDelete" name="btnDelete" class="btn">Delete</button>
<asp:Button ID="_btnDelete" runat="server" OnClick="_btnDelete_Click" style="display:none;" />

$('#btnDelete').click(function (e) {
    $.blockUI({ message: $('#divConfirmDeleteModal'), overlayCSS: { cursor: 'default' }, css: { cursor: 'default' }, baseZ: 5555 });
    return false;
});

$('#btnDeleteYes').click(function () {
    $('#<%=_btnDelete.ClientID%>').trigger('click');
});

$('#<%=_btnDelete.ClientID%>').click(function (e) { 
    // the delay happens here. if i put an alert here, it fires,
    // but then the page just loads until eventually the method gets called
    <%= ClientScript.GetPostBackEventReference(_btnDelete, string.Empty) %>; 
});

..and it's worked well for a while until now. I'm experiencing issues in IE (even version 10) - the _btnDelete_Click will take up to 2 minutes to get called after clicking the button that ultimately triggers it.

It feels too hacky and I was wondering if there is a better approach.

edit: here is another "correct" way to do it but I want to be able to use a fancier modal dialog and have that return true on a "yes" click, rather than using the browser's native confirm dialog.

edit2: I suppose what I'm asking is, is there a way to return a bool for an OnClientClick function that does more than one thing

like image 711
notAnonymousAnymore Avatar asked Jul 10 '13 18:07

notAnonymousAnymore


1 Answers

If you manually trigger click event in client script, your application won't be able function properly with mobile browser's Go button.

Here is how you can intercept the button's server side click event without manually triggering it by yourself at client side.

<script type="text/javascript">
    function clientClick() {
        if (confirm("Are you sure you want to delete?")) {
            // Do something at client side before posting back to server
            return true;
        }
        return false;
    }
</script>

<asp:Button runat="server" ID="DeleteButton" Text="Delete" 
    OnClick="DeleteButton_Click" OnClientClick="return clientClick();" />

You can do a lot of fancy stuffs with ASP.Net MVC. However, they create a lot of problem in traditional ASP.Net.

like image 169
Win Avatar answered Nov 14 '22 12:11

Win