【发布时间】:2017-08-30 21:11:23
【问题描述】:
我有一个 ajax post 方法可以将新记录添加到数据库中,该过程本身可以正常工作,并且我的服务器端代码会捕获错误(重复输入等)。当发生错误时,ajax 方法不会“看到”它,总是调用“成功”函数。这是我的ajax post方法
$.ajax({
url: '@Url.Action("Add", "Organisation")',
data: $form.serialize(),
async: true,
type: 'POST',
error: function (returnval) {
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
},
success: function (returnval) {
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
})
以及我控制器上的操作方法
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Add(OrganisationEditCreateViewModel data)
{
InsertOrganisationRequest request = new InsertOrganisationRequest();
IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
var model = mapper.Map<OrganisationEditCreateViewModel, OrganisationDto>(data);
request.organisation = model;
var response = this._organisationService.InsertOrganisation(request);
if (response.isSuccess)
{
return Json(new { success = true, responseText = "New organisation added successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = false, responseText = "Error adding new organisation : " + response.Message }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false, responseText = "Error adding new organisation : Invalid input" }, JsonRequestBehavior.AllowGet);
}
因此,当我插入重复记录时,服务器端代码会捕获此记录,并将此代码分支返回给我的 ajax 调用
return Json(new { success = false, responseText = "添加新组织时出错:" + response.Message }, JsonRequestBehavior.AllowGet);
但是ajax调用总是调用这段代码
success: function (returnval) {
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
错误部分永远不会被调用,我做错了什么?
【问题讨论】:
-
您的方法中没有任何地方抛出异常,因此它不会命中
error函数。你需要检查returnval.success的值
标签: ajax asp.net-mvc error-handling controller actionmethod