【问题标题】:Ajax JSON call to back-end function always triggers error response, even though function works correctly对后端函数的 Ajax JSON 调用总是触发错误响应,即使函数正常工作
【发布时间】:2017-08-05 11:08:52
【问题描述】:

我有以下 JSON Ajax 调用:

$.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")
});

调用这个函数:

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 });
}

该功能有效,因为数据库已正确更新,但error: 功能:

error: alert("Error Saving Data - changes not saved to database");

总是被解雇。 (我假设根据success: 函数,行 id 也没有更新。)

【问题讨论】:

  • 尝试将try catch块放入后端代码中,看看是否有任何错误发生。

标签: c# json ajax


【解决方案1】:

将function 分配给error:

error: function() {
  alert("Error Saving Data - changes not saved to database");
}

【讨论】:

    【解决方案2】:

    尝试返回一个 int 而不是 Json。

    我发现很多时候,当您错误地声明数据类型或返回不正确的数据时,有时会发生这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2015-11-12
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多