我正在尝试使用Ajax发布保存更改。我似乎在执行控制器方法之前就已经碰到了Ajax方法的fail事件。我想要成功返回“ 0”或“ 1”,或者将其他任何错误消息作为字符串返回给我的Ajax方法。我在这里想念什么? 下面是我的控制器和Ajax post方法的摘录。
Assets.Launch = {
ProductService: function ($stockItemId, $stockItemName, successCallback, failureCallback) {
var data = {
"stockItemId": $stockItemId,
"stockItemName": $stockItemName
};
$.ajax({
url: "/Purchasing/AddEditProductService",
type: "POST",
data: data
})
.done(function (result) {
if (result === "0") {
successCallback($stockItemName + " Successfully added");
}
else if (result === "1") {
successCallback($stockItemName + " Successfully updated");
}
else {
failureCallback(result);
}
})
.fail(function (jqxhr, textStatus, errorThrown) {
failureCallback(errorThrown);
});
}
};
public JsonResult AddEditProductService(int? stockItemId, string stockItemName)
{
string errorToReport = "";
bool isDuplicate = false;
bool isAdding = (stockItemId == 0);
StockItems entity;
using (var ctx = iuow)
{
if (isAdding)
{
entity = new StockItems();
}
else
{
entity = ctx.StockItems.Find(e => e.StockItemId == stockItemId).FirstOrDefault();
}
................
try
{
if (isAdding)
{
ctx.StockItems.Add(entity);
ctx.SaveChanges();
return Json("0");
}
else
{
ctx.StockItems.Update(entity);
ctx.SaveChanges();
return Json("1");
}
}
catch (DbUpdateException ex)
{
if (ex.InnerException != null)
{
var sqlException = ex.InnerException as SqlException;
isDuplicate = IsDuplicate(sqlException);
if (isDuplicate)
{
errorToReport = "Cannot insert duplicate key [" + stockItemName + "]";
}
else
{
errorToReport = sqlException.Message;
}
}
return Json(errorToReport);
}
catch (Exception exception)
{
errorToReport = (exception.InnerException == null) ? exception.Message : exception.InnerException.Message;
_logger.LogError(errorToReport);
return Json(errorToReport);
}
}
}