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">
              ×
              </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);
    }
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);
What do I have to do for the correct display of the page??? I also accept other ways to validate...


Thank you Netinho, I’ll test!
– Rafael Arthur
I didn’t quite understand your answer. It is possible to show me how the $.ajax complete would look?
– Rafael Arthur
@Rafaelarthur I edited the answer and includes the full ajax. Att.
– Netinho Santos
Thanks, it worked out!
– Rafael Arthur