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

1

Hello, I'm developing an application in asp.net core 2.0. I have a div with asp-validation-summary for the display of modelState errors.

follows:

<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. Following:

$(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 in 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);
    }

Result:

MYDIFFICULTY:IhaveapagewhereIworkwithalistthatI'maddingitemsviajavascript.ThenIperformPOSTviaAJAX,andinthecontrollerIgetthedatanormallyandthemodelstatealsodoesthevalidations.TheproblemisthatifthemodelStateisnotvalidandIreturntheviewtheerrorsarenotappearing...

IsthereanythingtodowithPOSTbeingviaajax???

Followthecode:

varurl="/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 have as a result:

What do I have to do to display the page correctly ??? I also accept other ways to do the validation ...

    
asked by anonymous 16.08.2018 / 16:26

1 answer

0

You can return a 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);

            }
        }
    });
    
16.08.2018 / 17:56