Here I gave one example of jQuery Ajax POST method, but problem with that example is that you don't know if returned JSON is wrong. Now I will give example when .NET side returns wrong JSON, and error handling in jQuery.
index.html remains same:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<script defer type="text/javascript" src="lib/jquery-3.5.1.js"></script>
<script defer type="text/javascript" src="js/index.js"></script>
</head>
<body>
<button id="button" type="button">Click Me!</button>
</body>
index.js:
$( "#button" ).click(function() {
var json = JSON.stringify({"cities": ["Aurel Vlaicu", "Asquins", "Arnoldstein"]});
$.ajax({
url: "api/Empty/",
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success.");
}
}).done(function (data) {
try {
json = $.parseJSON( JSON.stringify(data));
} catch (e) {
alert("Error not JSON. " + e.message)
}
}).error(function (xhr, ajaxOptions, thrownError) {
alert("Error.");
}).fail(function (data) {
alert("Sorry. Server unavailable. ");
});
});
.NET side:
[HttpPost]
public ActionResult Get([FromBody] Filter filter)
{
string returnValue = string.Empty;
foreach (var city in filter.cities)
{
returnValue = $"{city}, {returnValue}";
}
return Ok(JsonSerializer.Serialize(returnValue));
}
Notice that in "$.ajax.done" I added try..catch block, and JSON.stringify because of dataType: "json" jQuery will automatically parse string into JSON.