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