I’m having trouble with my web application. When I try to save data to the database using an AJAX call, everything seems to work fine but no records actually get saved.
Here’s my frontend JavaScript code:
var employee = {};
employee.FullName = $("#inputName").val();
employee.Years = $("#inputAge").val();
employee.ContactEmail = $("#inputEmail").val();
$.ajax({
method: "POST",
url: "Main.aspx/SaveEmployee",
data: "{'employeeData':'" + JSON.stringify(employee) + "'}",
success: function (result) {
$("#messageSuccess").text("Record saved!");
$("#messageSuccess").show();
},
error: function (result) {
alert(result.responseJSON);
}
});
This connects to my server-side method:
[WebMethod]
public static void SaveEmployee(string employeeData)
{
JavaScriptSerializer parser = new JavaScriptSerializer();
Employee emp = parser.Deserialize<Employee>(employeeData);
DataMethods.SaveEmployee(emp);
}
Which calls this method in DataMethods.cs:
[WebMethod]
public static void SaveEmployee(Employee emp)
{
EmployeeManager manager = new EmployeeManager();
manager.SaveEmployee(emp);
}
And finally the database operation:
public void SaveEmployee(Employee emp)
{
if (string.IsNullOrWhiteSpace(emp.FullName))
{
throw new Exception("Name is required");
}
if (string.IsNullOrWhiteSpace(emp.ContactEmail))
{
throw new Exception("Email is required");
}
using (companyEntities context = new companyEntities())
{
context.employee.Add(emp);
context.SaveChanges();
}
}
The success callback fires and no errors show up in the browser console, but when I check the database there’s nothing there. This same logic works perfectly in my desktop application. Any ideas what might be going wrong?