Reputation: 53
This is my view, ajax request and the controller respectively. The problem is when I save something, sometime it hits the success method in the ajax request and sometimes not.
View
<form id="myForm">
<div>
<div class="row">
<div class="col-12">
<label asp-for="RoleName" class="control-label"></label>
</div>
</div>
<div class="row">
<div class="col-10">
<input asp-for="RoleName" class="form-control" />
<span asp-validation-for="RoleName" class="text-danger"></span>
</div>
<div class="col-2">
<div>
<button value="Index" id="btnSave" class="btn btn-success" data-toggle="tooltip" data-placement="bottom" title="Save !"><i class="fa fa-save"></i></button>
</div>
</div>
</div>
</div>
</form>
Ajax request
$("#btnSave").click(function () {
debugger;
var RoleObj = { RoleName: $('#RoleName').val() };
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: '@Url.Action("Index", "MasterRoles")',
dataType: "json",
data: JSON.stringify(RoleObj),
headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() }
}).done(function (response) {
alert('Success');
}).fail(function (jqXHR, textStatus) {
alert('Error');
});
});
This is the controller which is invoked in the post method. Data is posting the only problem is that return values in getting in the success sometimes but not all the time
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> Index([Bind("RoleName")] [FromBody] MasterRole masterRole)
{
try
{
if (ModelState.IsValid)
{
_context.Add(masterRole);
await _context.SaveChangesAsync();
return Json(new { status = "1", roleList });
}
else
{
return Json(new { status = "2", roleList });
}
}
catch (Exception ex)
{
return Json(new { status = "2" });
}
}
Upvotes: 1
Views: 645
Reputation: 6969
I have a suspicion your form is being submitted on button click which is why you sometimes don't see the ajax function being called.
You need to ignore the default mouse click on the button as this will submit the form:
$("#btnSave").click(function (e) {
e.preventDefault();
debugger;
var RoleObj = { RoleName: $("#RoleName").val() };
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: '@Url.Action("Index", "MasterRoles")',
dataType: "json",
data: JSON.stringify(RoleObj),
headers: {
RequestVerificationToken: $(
'input:hidden[name="__RequestVerificationToken"]'
).val(),
},
})
.done(function (response) {
alert("Success");
})
.fail(function (jqXHR, textStatus) {
alert("Error");
});
});
Upvotes: 1