Stuck into a weird problem. My ajax call is showing response as following:
My ajax response is not going to success function.
Asp.Net Core code:
[HttpPost]
[AutoValidateAntiforgeryToken]
public async Task<JsonResult> Create(CityCreateUpdateVm vm)
{
if(ModelState.IsValid)
{
Thread.Sleep(5000);
var response = await _cityService.Create(vm);
return Json(response);
}
return Json(new { });
}
_cityService service is returning following object:
public class AjaxResponseVm
{
public List<string> Errors { get; set; }
public bool IsOk
{
get
{
return Errors.Count > 0 ? false : true;
}
}
public AjaxResponseVm()
{
Errors = new List<string>();
}
public void AddError(string error)
{
if (Errors != null && error != string.Empty)
{
Errors.Add(error);
}
}
}
Here is my form:
<form asp-controller="city" asp-action="create" id="cityCreateFrom" method="post" onsubmit="return CreateResource('cityCreateFrom', 'City created successfully.')">
<partial name="_CityInfo.cshtml" />
</form>
Parial view just have 2 text boxes.
Here is my jQuery code:
function CreateResource(formid, successfulmessage) {
var form = '#' + formid;
if ($(form).valid()) {
Swal.fire(
{
type: "success",
text: "Working...",
allowOutsideClick: false
});
Swal.showLoading();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
async: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
Swal.close();
if (response.isOk) {
Swal.fire(
{
title: successfulmessage,
icon: "success",
type: "success",
confirmButtonClass: "btn bg-gradient-primary",
confirmButtonText: "Ok",
allowOutsideClick: false,
})
.then((result) => {
if (result.isConfirmed) {
window.location.href = 'index';
}
});
}
else {
var errorList = '<ul>';
}
},
error: function (response) {
Swal.fire(
{
title: "Something went wrong.",
icon: "error",
type: "error",
confirmButtonClass: "btn bg-gradient-danger",
confirmButtonText: "Ok",
allowOutsideClick: false,
});
},
});
}
return false;
}
Response is correctly returning from Asp.Net Core. The problem is response is not going to the success function but it is showing JSON as shown in above picture.
Any help will be appreciated.
Regards D
Update 1
I don't know why it is submitting this request:
Not the content-type here. I don't know why it is "application/x-www-form-urlencoded" instead of json. I think this is the problem.

