Hello Team,
Please this is a simple ajax code I thought could work but fail to save the data into the database, kindly assist me please
function saveSalary() {
var model = {};
model.SalaryId = $("#salaryId").val();
model.PayDate = $("#date1").val();
model.Name = $("#name").val();
model.Advance = $("#advance").val();
model.Month = $("#month").val();
model.FinalPay = $("#finalsalary").val();
model.PayBy = $("#by").val();
var data = JSON.stringify({
model: model
});
swal("Save!", "Salary save successfully", "success");
$("#success-message").click(function (e) {
Swal.fire({
title: "Good job!",
text: "You clicked the button!",
icon: "success",
buttonsStyling: false,
confirmButtonText: "Confirm me!",
customClass: {
confirmButton: "btn btn-primary"
}
});
});
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/SaveSalary',
data: data,
sucess: function (result) {
if (result == true) {
Reset();
getAllSalary();
dataTable-Salary.ajax.reload();
$("#SalaryModal").modal('hide');
}
else {
swal("Save Fail");
}
},
error: function () {
swal("Error!");
}
});
}
ENTITY DATA CLASS
public class SalaryViewModel
{
public int SalaryId { get; set; }
public string PayDate { get; set; }
public string Name { get; set; }
public Nullable
public string Month { get; set; }
public Nullable
public string PayBy { get; set; }
}
Emmmanuel FIADUFEPosted May 19, 2023, 10:21 AM
Thank you Vishal, when I Use below code to pass the data to the controller to the database it works fine, but when I created ViewModel and I was trying to pass the data through the ViewModel to the controller, it fails to save without any error message.
public JsonResult SaveSalary(tblSalary salaries)
{
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
bool isSuccess = true;
if (salaries.SalaryId > 0)
{
db.Entry(salaries).State = EntityState.Modified;
}
else
{
db.tblSalaries.Add(salaries);
}
try
{
db.SaveChanges();
}
catch (Exception)
{
isSuccess = false;
}
return Json(isSuccess, JsonRequestBehavior.AllowGet);
}
Vishal YelvePosted May 19, 2023, 6:46 AM
Hi
What error you are getting. ??
If in controller you are not getting Data then try this.
Emmmanuel FIADUFEPosted May 18, 2023, 6:38 PM
CONTROLLER
[HttpPost]
public ActionResult SaveSalary(SalaryViewModel model)
{
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
if (model.SalaryId > 0)
{
tblSalary salary = db.tblSalaries.SingleOrDefault(x => x.SalaryId == model.SalaryId);
salary.SalaryId = model.SalaryId;
salary.PayDate = model.PayDate;
salary.Name = model.Name;
salary.Advance = model.Advance;
salary.Month = model.Month;
salary.FinalPay = model.FinalPay;
salary.PayBy = model.PayBy;
db.SaveChanges();
}
return Json(model, JsonRequestBehavior.AllowGet);
}