My Problem is that, the result from the controller replaces the entire view with its content, instead of just updating an element in the view with its JSON.
I tried to change data type in AJAX-Post, but it didn’t work
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(DTO_SomeObject surveyData)
{
...
if (!ModelState.IsValid)
{
//var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList();
//return Json(new { success = false, errors = string.Join("<br>", errors) });
var errors = ModelState.Values.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage)
.Aggregate((current, next) => current + "<br>" + next);
return Json(new { success = false, errors });
}
}
Here is the frontend with it’s HTML and razor content:
@model SurveyRetirementAspNet.Models.DTO_SomeObject
@* @model Datalayer.Models.Global.Classes.DTO_SomeObject *@
@{
ViewData["Title"] = "Umfrage: " + @Model.Name;
}
<h1 class="text-center mt-4 mb-5"><u style="font-weight:bolder">@Model.Name</u></h1>
<div class="container">
@* <form asp-action="Index" method="post" class="card card-body shadow-lg p-5 border-0"> *@
<form id="surveyForm" asp-action="Index" method="post" class="card card-body shadow-lg p-5 border-0">
...
<div class="separator"></div>
<div id="errorMessages"></div>
<button type="submit" class="btn btn-primary w-100">Umfrage absenden</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#surveyForm').on('submit', function (e) {
e.preventDefault(); // Prevent normal form submission
var formData = $(this).serialize(); // Serialize the form data
$.ajax({
type: 'POST',
url: $(this).attr('action'), // Use the action from the form
data: formData,
dataType: 'json', // Expect JSON response from the server
success: function (response) {
if (response.success) {
window.location.href = '/path/to/success/page'; // Redirect on success
} else {
// Display error messages returned from the server
// $('#errorMessages').html(response.errors);
console.log("Ajax error"); // Fehler anzeigen, wenn Ajax fehlschlägt
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('#errorMessages').html('Error: ' + textStatus + ' - ' + errorThrown);
}
});
});
});
</script>
How should it be right?