【发布时间】:2018-02-26 08:39:00
【问题描述】:
我的问题是 ajax 中的成功功能有效但错误无效但如果添加到 contentType: 'application/json' 工作总是错误功能。
$.ajax({
type: "POST",
data: { pollCodeInput: pollCodeInput, pollNameInput: pollNameInput, promotionPoints: promotionPoints },
url: "http://Work.local/mvc/KeyFacts/CreatePoll2",
//contentType: 'application/json',
success: function () {
openNav();
$('#modal').removeClass('modal-open');
},
error: function () {
alert("error!");
}
});
});
当我调试时,我的控制器工作正常。这是我的控制器;
[HttpPost]
public ActionResult CreatePoll2(string pollCodeInput, string pollNameInput, int promotionPoints = 0)
{
MethodResult result = BusinessComponentRegistry.SingleInstance.PollManager.Create(pollCodeInput,
pollNameInput, 0);
if (result.HasErrors)
{
ViewBag.ErrorCreatePoll = result.Messages.ToString();
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
else
{
ViewBag.SuccessCreatePoll = result.Messages.ToString();
return Json(new { success = true, error = false, responseText = "Success!!" }, JsonRequestBehavior.AllowGet);
}
}
【问题讨论】:
-
查看documentation,了解如何从错误处理程序中获取一些有用的信息,而不仅仅是警告“错误!”
-
如果你返回一个成功的结果,你为什么期望
error:处理程序启动?仅仅因为成功的结果包含一个布尔值,它仍然是成功的。 -
您要么需要在
success:处理程序中处理success=false,要么不返回有效的(200)结果,例如if (result.HasErrors) throw new InvalidOperation(Not supported')` -
你试过这个“contentType:”application/json; charset=utf-8","
-
实际上,我不太了解,但是 if(result.HasErrors) 函数适用于例如:用户输入 null 或现有 pollCode 并且即使显示成功函数不保存现有 pollCode 它也可以正常工作或 null pollCode
标签: jquery ajax asp.net-ajax