admin管理员组

文章数量:1417686

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

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

Share Improve this question edited May 23, 2017 at 12:06 CommunityBot 11 silver badge asked Jul 10, 2013 at 18:36 notAnonymousAnymorenotAnonymousAnymore 2,6879 gold badges53 silver badges74 bronze badges 6
  • Why not handle this server-side? – Chris Cannon Commented Jul 10, 2013 at 18:41
  • What do you mean? With ClientScript.RegisterStartupScript? I want to handle it client-side I think. – notAnonymousAnymore Commented Jul 10, 2013 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 Commented Jul 10, 2013 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 Commented Jul 10, 2013 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 Commented Jul 12, 2013 at 19:17
 |  Show 1 more ment

3 Answers 3

Reset to default 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.

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./ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis./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./ajax/libs/jqueryui/1.8/themes/base/jquery.ui.all.css"/>

Repressed memories are awakened - i was fighting the same battle with asp 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 webforms.

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

本文标签: javascriptBest way to intercept a Button postbackStack Overflow