Need to close Jquery UI dialog from controller action in MVC 5

1k Views Asked by At

I am building a site where I am calling a partial view within a jquery ui dialog box. Within the partial view there is a 'save' button that commits the data on the form to the database. Currently it redirects to a different view. I would like it to instead close the dialog box. I am unable to get it to properly call the function to close the dialog box.

Here is my code:

In the View:

<script type="text/javascript">
            $.ajaxSetup({ cache: false });
            $(document).ready(function () {
                $(".diagSave").on("click", function (e) {
                    e.preventDefault();
                    $("<div></div>")
                    .dialog({
                        title: $(this).attr("data-dialog-title"),
                        modal: true,
                        width: 1000,
                        success: function () {
                        $('#diagSave').dialog('close');
                    }
                    })

                    .load(this.href);
                })

            });
</script>

In the Controller:

return Json(new { success = true }, JsonRequestBehavior.AllowGet);

Can someone please help point out how I can accomplish this?

2

There are 2 best solutions below

1
On

An alternative would be to handle the save click in jquery, use .serialize to send the form collection to your controller, then close the dialog.

var formvalues = $('#yourformparentdiv form').serialize();
$.ajax({
     url: siteRoot + 'Home/YourControllerMethod',
     data: formvalues,
     async: true,
     type: "POST",
     ...
3
On

If you need to handle the close and save from the partialview you need to handle the close within a click event there.

$("#partialview_savebutton").click(function(e){
    var $dlg = $(this).parents(".ui-dialog");
    //save the data
    $dlg.dialog("close");
});

You need to ensure that this method is bound when you load the content into your dialog.

I generally include this at the end of my dialog open routine.

if(typeof initDlg == 'function') initDlg();

And then bind my event handlers and configure any validation I need within a defined initDlg(){} defined in my partialview.