Search code examples
jqueryasp.netjquery-ui-dialogcode-behindclientscript

Using ClientScript.RegisterStartupScript with JQuery dialog


I have the following method in aspx code behind which displays a jquery dialog. Is it possible for this method to return true if the user clicks "Submit" on the dialog?

    Sub DisplayDialog()
        Dim title As String = "title"
        Dim content As New StringBuilder()
        content.Append(@"<script type=text/javascript>
          $(function () {
           $('#dialog')
            .dialog({
            title: 'title',
            modal: 'true',
            buttons: {
                'Submit': function () { 
                },
                'Cancel': function () {
                    $(this)
                        .dialog('close');
                }
            }
        });
    });
</script>")
     ClientScript.RegisterStartupScript(Me.[GetType](), title, content.ToString())
    End Sub

EDIT:

Here is a more complete picture of what I have:

Sub GridView1_onRowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
    Select Case e.CommandName
        Case "Upload"
            DisplayDialog()
            //Get result here from jquery dialog. Do something if result was true             
        Case "Something"
     End Select
End Sub

Solution

  • If you want to use the return of the Modal Dialog in order to perform an action, this is the pattern you should follow:

    <script type="text/javascript">
        $(function () {
            var $dialog = $("#dialog");
            var $foo = $("input:submit[id$=foo]");
            var confirmed = false;
    
            $dialog.hide();
    
            $dialog.dialog({
                width: "300px",
                modal: true,
                autoOpen: false,
                buttons: {
                    OK: function (e) {
                        $dialog.dialog("close");
                        confirmed = true;
                        $foo.click();
                    },
                    Cancel: function (e) {
                        $dialog.dialog("close");
                        confirmed = false;
                    }
                }
            });
    
            $foo.click(function (e) {
                if (!confirmed) {
                    $dialog.dialog("open");
                }
    
                return confirmed;
            });
        });
    </script>
    
        <div>
            <asp:Button Text="Submit" runat="server" ID="foo" OnClick="foo_Click" />
        </div>
        <div id="dialog">
            <asp:Label Text="Are u sure u wanna do it?" runat="server" />
        </div>
    

    Basically you use a flag to indicate what button was pressed, and you return that flag when clicking a button.

    You could take this sample and adjust it to fit your specific needs

    This is the full working Example on my GitHub