MVC - Keep PartialView loaded when ModelState is not valid

0

I have a simple registration screen that, when selected new record, a modal (which is a partialview in the project) is opened for the user to enter the fields for registration.

The call to the view is done through Jquery:

$("#btn-Incluir").click(function () {
    $("#modalCadastro").modal({
        backdrop: 'static',
        keyboard: true
    }, 'show');
});

The save button of PartialView is of type submit , and inside my controller I have the method below:

public virtual ActionResult Salvar(TViewModel model)
    {
        if (ModelState.IsValid)
        {
            if (model.Operacao.Equals("I"))
                Inserir(model);
            else
                Atualizar(model);                

            return RedirectToAction(NmView);

        }
        else
        {
            return PartialView(model);
        }
    }

The problem is that when ModalState is invalid, error below is displayed:

  

The partial view 'Save' was not found in or view engine supports the searched locations. The following locations were searched

If I change and return the path of my partial view , the system only displays the partial view , no longer as modal child of the main page. >

How do I make it work when ModalState is invalid, continue with the modal open and only display errors on the page via ValidationMessageFor .

Thank you!

    
asked by anonymous 13.07.2016 / 21:02

1 answer

2

There are a lot of bad practices here. Within your Salvar method, you have:

public virtual ActionResult Salvar(TViewModel model)
{
    if (ModelState.IsValid)
    {
        if (model.Operacao.Equals("I"))
            Inserir(model);
        else
            Atualizar(model);                

        return RedirectToAction(NmView); // Isto muda o estado atual da página

    }
    else // Desnecessário
    {
        return PartialView(model); // Isto não necessariamente muda o estado atual da página.
    }
}

In addition, you do not have a Partial named Salvar.cshtml , which causes the error.

If the idea of the Salvar method is not to modify the current state of the page, the method should be implemented as:

public virtual JsonResult Salvar(TViewModel model) { ... }

And the method must be called through Ajax.

If the idea is to actually change the current state of the page, you can redirect to the same document, but opening the modal to display, for example, validation messages, is not guaranteed:

public virtual ActionResult Salvar(TViewModel model)
{
    if (ModelState.IsValid)
    {
        if (model.Operacao.Equals("I"))
            Inserir(model);
        else
            Atualizar(model);                

        return RedirectToAction(NmView);
    }

    return View(model); // Troque aqui.
}
    
13.07.2016 / 22:38