Wednesday, July 20, 2011

Using jQuery UI Dialog as a confirmation box for an ASP.Net button

This will add a jQuery UI Dialog confirmation when clicking a button in asp.Net. This is a non-generic, one button <-> one dialog example.

The button:
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" CausesValidation="true" OnClientClick="jQuery('#confirmation').dialog('open'); return false;" />


 
The Dialog display div:
    <div id="confirmation" title="Submit Form?">
        <span class="ui-icon ui-icon-alert" style="margin0 7px 50px 0floatleft;"></span>
        <span>Are you sure you would like to submit this form?</span>
    </div>

The Javascript:
    <script type="text/javascript">
        jQuery(document).ready(function() {
            $('#confirmation').dialog({
                autoOpen: false,
                modal:true,
                buttons: {
                    "Submit"function() { $(this).dialog("close"); <%= Page.ClientScript.GetPostBackEventReference(this.btnSubmit, string.Empty) %>; },
                    "Cancel"function() { $(this).dialog("close"); }
                }
            });
         });
    </script>

NOTE:  As sisyphus has pointed out below, this does not call client side validation.  I rarely use this method for submitting anything requiring it, so it never occured to me to include it.   I'm including code that should allow client side validation to occur.  It's not tested, but I'm pretty sure it is accurate :)
 
The Javascript with Client Side Validation invoked:    
<script type="text/javascript">
        jQuery(document).ready(function() {
            $('#confirmation').dialog({
                autoOpen: false,
                modal:true,
                buttons: {
                    "Submit": function() { $(this).dialog("close"); if (Page_ClientValidate()) <%= Page.ClientScript.GetPostBackEventReference(this.btnSubmit, string.Empty) %>; },
                    "Cancel": function() { $(this).dialog("close"); }
                }
            });
         });
    </script>




2 comments:

sisyphus

Thanks for the useful post. It might be worth noting that this approach doesn't invoke client side validation.

timbck2

When I try this example, I get an exception in the Chrome Javascript debugger: "Uncaught TypeError: Object [object Object] has no method 'dialog'", and no dialog pops up. Also, the "confirmation" div is rendered in the window as plain text when the page is loaded.