I have the following JSON Ajax call:
$.ajax({
url: '@Url.Action("AddOrUpdateTimeEntry", "TimeEntries")',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: payload,
success: function (data) {
var id = data.TimeEntryID;
$(this).parent().parent().parent().attr('id', id);
}
error: alert("Error Saving Data - changes not saved to database")
});
which calls this function:
public ActionResult AddOrUpdateTimeEntry(TimeEntryData ted)
{
int rowId = Convert.ToInt16(ted.RowId.Split('_')[1]);
// If RowId = 0, it's a new row so create, otherwise update
bool IsNewRow = rowId == 0;
int hours = ted.Hours;
TimeEntry te;
if (IsNewRow)
{
te = new TimeEntry();
te.ClientID = ted.ClientID;
te.TaskTypeID = ted.TaskTypeID;
}
else
{
te = (from t in db.TimeEntries
where t.TimeEntryID == rowId
select t).FirstOrDefault();
}
switch (ted.DayOfWeek)
{
case "Mon":
te.MonHours = hours;
break;
...
}
if (IsNewRow) // New row, so create a new entry in database
{
db.TimeEntries.Add(te);
}
db.SaveChanges();
var id = te.TimeEntryID;
return Json(new { TimeEntryID = id });
}
The function works, in that the database is updated correctly, but the error:
function:
error: alert("Error Saving Data - changes not saved to database");
is always fired. (I assume that the row id is not updated either as per the success:
function.)
答案 0 :(得分:1)
Assign a function
to error
:
error: function() {
alert("Error Saving Data - changes not saved to database");
}
答案 1 :(得分:1)
Try returning an int rather than Json.
I find that a lot of the time this can sometimes happen when you mis-declare the datatype or return incorrect data.