How to display Modelstate errors when POST is done by AJAX?

Asked

Viewed 231 times

1

Hi, I’m developing an Asp.net core 2.0 application. I have a div with Asp-validation-Summary for displaying model errors.

follow:

<div asp-validation-summary="All"
  class="validation-summary alert alert-danger alert-dismissable ">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">
              &times;
              </span>
            </button>
            <h4>O formulário possui erros:</h4>
</div>

I also have a javascript that checks for errors and displays the div or escode. Follows:

$(function () {
$('.validation-summary-errors').each(function () {
    $(this).addClass('alert');
    $(this).addClass('alert-danger');
});

$('form').each(function () {
    $(this).find('div.form-group').each(function () {
        if ($(this).find('span.field-validation-error').length > 0) {
            $(this).addClass('has-error');
            $(this).find('span.field-validation-error').
               removeClass('field-validation-error');
        }
    });
});

});

And on the controller:

[HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(SetorVM vm)
    {
        if (ModelState.IsValid)
        {
            _setorAppService.Adicionar(vm);
            return RedirectToAction("Index");
        }
        else
        {
            ModelState.AddModelError("", "O seu formulário possui erros! Corrija-os para continuar.");
        }

        return View(vm);
    }

Upshot: inserir a descrição da imagem aqui

MY DIFFICULTY: I have a page where I work with a list that I add items via javascript. Then I perform the POST via AJAX, and in the controller I receive the data Normally and the modelstate also makes the validations. The problem is that if modelState is not valid and I return the view is not showing errors...

It has something to do with the POST Being via ajax???

Follows the code:

var url = "/Material/Create";

$.ajax({
    url: url
    , type: "POST"
    , datatype: "json"
    , headers: headersadr
    , data: {xxxxxxx }
    , success: function (data) {
        if (data.resultado > 0) {
        }
        else {
            var divItens = $("#divValidationSummaryShow");
            divItens.empty();
            divItens.show();
            divItens.html(data);

        }
    }
});

CONTROLLER:

  if (ModelState.IsValid)
        {
            _materialAppService.Adicionar(vm);
            return RedirectToAction("Index");
        }
        else
        {
             ModelState.AddModelError("", "O seu formulário possui erros! Corrija-os para continuar.");
        }
        return View(vm);

And I got as a result: inserir a descrição da imagem aqui

What do I have to do for the correct display of the page??? I also accept other ways to validate...

1 answer

0


You can return one Json containing the errors of ModelState

Action

 if (!ModelState.IsValid)
 {
     return Json(new { success = false, errors = ModelState.Values.Where(i => i.Errors.Count > 0) });
 }

Ajax

 $.ajax({
        url: url,
        type: "POST",
        datatype: "json",
        headers: headersadr,
        data: {
            xxxxxxx
        },
        success: function(data) {
            if (data.errors.length > 0) {
                for (var i = 0; i < response.errors.length; i++) {
                    var error = response.errors[i];
                    //Aplique os erros na sua div validation-summary
                }
            } else {
                var divItens = $("#divValidationSummaryShow");
                divItens.empty();
                divItens.show();
                divItens.html(data);

            }
        }
    });
  • Thank you Netinho, I’ll test!

  • I didn’t quite understand your answer. It is possible to show me how the $.ajax complete would look?

  • @Rafaelarthur I edited the answer and includes the full ajax. Att.

  • Thanks, it worked out!

Browser other questions tagged

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