How to throw controller errors and capture them in an Ajax - Asp.net Core MVC request

Asked

Viewed 46 times

0

I’m using AJAX to make a request and the return is a Partialviewresult. In the request, I am passing the personal model.

Someone knows how to help me?

CONTROLLER:

[HttpPost]
[Route("pessoa-gerenciar/change-forma-contato")]
public PartialViewResult ChangeFormaContato([FromBody] PessoaFormaContatoParametrosChangeViewModel pessoaFormaContatoParametrosChangeViewModel)
{
    if (pessoaFormaContatoParametrosChangeViewModel == null)
    {
        Return //Retorne o erro: Falha ao realizar a requisição no servidor.
    }

    ViewBag.indice_new = pessoaFormaContatoParametrosChangeViewModel.RowIndice;
    return PartialView("~/Views/Pessoa/PessoaFormaContato/_PessoaFormaContatoAdd.cshtml", _pessoaFormaContatoAppService.ChangePessoaContato(pessoaFormaContatoParametrosChangeViewModel));
}

AJAX:

$.ajax({
    url: "/pessoa-gerenciar/change-forma-contato",
    type: "POST",
    data: JSON.stringify(pessoaFormaContatoParametrosChangeViewModel),
    contentType: "application/json",
    success: function (data) {

        $this.closest(".row").replaceWith(data);
        set_plugins_pessoa_forma_contato_run_time(rowIndice);
        stopLoadModalInside();

    },
    error: function () {
        stopLoadModalInside();
        alert("Oops! Algo deu errado.");
    }
});
  • You just want to return a message?

1 answer

0


Puts a string inside the if at this point:

[HttpPost]
[Route("pessoa-gerenciar/change-forma-contato")]
public PartialViewResult ChangeFormaContato([FromBody] PessoaFormaContatoParametrosChangeViewModel pessoaFormaContatoParametrosChangeViewModel)
{
    if (pessoaFormaContatoParametrosChangeViewModel == null)
    {
        Return 'Falha ao realização requisição'; //Retorne o erro
    }

    ViewBag.indice_new = pessoaFormaContatoParametrosChangeViewModel.RowIndice;
    return PartialView("~/Views/Pessoa/PessoaFormaContato/_PessoaFormaContatoAdd.cshtml", _pessoaFormaContatoAppService.ChangePessoaContato(pessoaFormaContatoParametrosChangeViewModel));
}

In Ajax you will rescue the information that comes through the variable date.

error: function (data) {
        stopLoadModalInside();
        alert("Oops! Algo deu errado." + data);
    }
  • It’s quite likely I need to display more than one message. I handled only the case of Model being null, but there is the possibility of being multiple rsrs messages.

  • Exact. if this is the case, go saving the messages in a variable and then return everything at once.

  • And to get this message with AJAX, I need to vailidar the return in the block: error: Function () { stopLoadModalInside(); Alert("Oops! Something went wrong."); } ?

  • I’ll write the answer

  • Thank you @Glenys Mitchell !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.