0

I have a dialog box that uses the Entity foo.
After I save the values from this dialog box I do the following :

    $('#SaveEditPQ').submit(); //jquery submit
    $("#NewQuickDlg.results").remove();  // clear the fields within the dialog Box
    $("#AddQuickDlg").dialog("close");   // close the dialog box.


Now ... the issue comes when i try to use (metadata) validating. I want to keep the Dialog Box open if the ModelState.IsValid is false.

This can be solved non-elegantly by extending my foo entity with a value that will get the value of the ModelState.IsValid and change my Jquery to :

$('#SaveEditPQ').submit(); 
    if ('@Model.IsValidVariable'==true)
    {
    $("#NewQuickDlg.results").remove(); 
    $("#AddQuickDlg").dialog("close");  
    }

Is this the best way to do this ?

Mihai Labo
  • 1,082
  • 2
  • 16
  • 40

1 Answers1

1

I was struggling with the same issue, but I solved it a different way. i didn't want to pollute my model with a hidden variable to close the dialog so what i did was redirect to a shared _close partialview. Then after my post, check if the close div was present and close the dialog. So my query looks like

$(document).on('click', "#SaveButton", function () {
    $.ajax({
        url: "/controller/Edit",
        type: "POST",
        data: $("form").serialize(),
        error: function (data) {
            var errorMessage = $.parseJSON(data.responseText);
        },
        success: function (data) {
            if (data) {
                if ($(data).attr('id') == 'close') {
                    $("#myDialog").dialog('close');
                }
                $("#myDialog").html(data);
                $("form :input:visible:enabled:first").focus();
            }
            else {
                $("#myDialog").html('no data');
            }
            return false;
        }
    });

So now I see the server-side validation in the dialog.

Here's the controller method

    [HttpPost]
    public ActionResult SaveEdit(SomeType viewModel)
    {
        if (!ModelState.IsValid)
        {
            PopulateDropDowns(viewModel);

            return PartialView(viewModel);
        }

        var someObject= _objectRepository.Get(viewModel.Id);

        //make some changes to someObject

        _objectRepository.Save(someObject);

        return PartialView("_close");
    }

So that also follows the PRG pattern

Fran
  • 6,440
  • 1
  • 23
  • 35
  • Thanks for the answer. Moved to a new issue for now ... Gonna give it a try and get back to you with the outcome :) – Mihai Labo Sep 06 '12 at 14:51