6

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

Community
  • 1
  • 1
notAnonymousAnymore
  • 2,637
  • 9
  • 49
  • 74
  • Why not handle this server-side? – Chris Cannon Jul 10 '13 at 18:41
  • What do you mean? With ClientScript.RegisterStartupScript? I want to handle it client-side I think. – notAnonymousAnymore Jul 10 '13 at 18:44
  • I wouldn't rely on JavaScript, especially if it is a public website, what if JavaScript is disabled or they are using a mobile browser with bad JavaScript support? What is it your trying to achieve? – Chris Cannon Jul 10 '13 at 18:48
  • I don't know any other way to intercept the button click, and I want to do js stuff when buttons are clicked, before doing a postback. The customer is fine with the site relying on js being enabled. – notAnonymousAnymore Jul 10 '13 at 18:52
  • I just made a sample page with the same layout and it didn't take very long to post. Maybe there's something else going? Other javascript blocking maybe? – Andrew Walters Jul 12 '13 at 19:17
  • It's very weird - the delay only happens in IE, and only on the second use of the button. So something whack is happening with ViewState which I couldn't be bothered to debug, hence this question. Think I'm gonna go with Bikonja's suggestion - seems the safest way. I guess I could provide exact steps to reproduce the problem, but it would just be for educational purposes :P (Maybe someone could then figure out exactly why the delay happens) – notAnonymousAnymore Jul 12 '13 at 20:07

3 Answers3

3

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.

Win
  • 61,100
  • 13
  • 102
  • 181
  • Can't wrap my head around how to show a fancier modal dialog (like BlockUI) instead of confirm('') and have a "yes" click return true – notAnonymousAnymore Jul 10 '13 at 20:59
  • 1
    Always return false in the OnClientClick of the button and add the actual postback button in the fancier modal dialog that will do the actual postback. Unless you have an iframe or something like that, this should be fine. After all, that is what you want to do - the "main" button shouldn't ever really do the action, the "Confirm" button should do the action, shouldn't it? – Bikonja Jul 12 '13 at 19:13
0

If you want to show a fancier modal dialog, you can use jQuery UI dialog widget. To be consistent with your example, please review the following code for the body element of an example web form:

<form id="form1" runat="server">
    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
    <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
    <div id="deleteConfirmationDialog" title="Warning!">Are you sure you want to delete?</div>
    <asp:Button ID="_btnDelete" runat="server" Text="Delete" OnClick="_btnDelete_ServerClick" OnClientClick="return _btnDelete_ClientClick();" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
    function doPostBack(theForm, eventTarget, eventArgument) {
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }

    function showConfirmationDialog(dialogSelector, callback, form, target) {
        $(dialogSelector).dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: [{
                text: "Yes",
                click: function () {
                    $(this).dialog("close");
                    callback(form, target, null);
                }
            },
            {
                text: "No",
                click: function () {
                    $(this).dialog("close");
                }
            }]
        });
    };

    function _btnDelete_ClientClick() {
        showConfirmationDialog("#deleteConfirmationDialog", doPostBack, $("#form1").get(0), "_btnDelete");
        return false;
    }

    $(document).ready(function () {
        $("#deleteConfirmationDialog").hide();
    });
</script>

The code behind associated with control "_btnDelete" (method "_btnDelete_ServerClick") will executed only in case you click on "Yes"button in the modal dialog be shown after "Delete" button is pressed. Do not forget to add the jQuery UI CSS file to the head section:

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.all.css"/>
Ricardo Sotolongo
  • 723
  • 11
  • 29
0

Repressed memories are awakened - i was fighting the same battle with asp.net Webforms 3.5 years ago. We had to implement ajax calls within a grid by pressing enter and showing a modal dialog to confirm the order in case the product had some remarks (like refurbished and so on).

Browsing through some old code fragments i have found all sort of javascript to prevent defaults and bubbling

// prevent the browser event bubbling for example posting the webform
function stopDefault(e) {

    if (e.preventDefault) {
        e.preventDefault();
        e.stopPropagation();

    } else {
        event.returnValue = false;
        event.cancelBubble = true;
        e.returnValue = false;
        e.cancelBubble = true;              
    }
}

and html / asp like this

<button type="button" 
     onclick="SearchProducts(event,this);">Search Products</button>
<asp:Button ID="btnSearch" ClientIDMode="Static" runat="server" 
 onclick="btnSearch_Click"  
 OnClientClick="SearchProducts(event,this)"
 UseSubmitBehavior="false"
 Text="Does nothing" />  

I ended up using only standard html buttons and avoided the asp:Button because it was less of a hassle to fight all the inbuilt functions and behind the scenes magic of asp.net webforms.

If avoiding asp:button is an option for you i can really recommend it.

surfmuggle
  • 5,527
  • 7
  • 48
  • 77
  • Thanks for the code snippets. I avoid them where I can, but for things like file uploads I think I'll use them. The transition to MVC is a slow one. – notAnonymousAnymore Jul 20 '13 at 21:35