我使用Ajax.BeginForm来调用我的应用程序来运行一些代码。出错,我想返回我将创建的自定义错误消息。
但是到目前为止我还没能做到。这就是我所拥有的:
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> Edit(UserViewModel model) {
Response.StatusCode = 500;
return Json(new { error = "Broken" });
}
Ajax.BeginForm:
@using (Ajax.BeginForm("Edit", "User", new AjaxOptions { HttpMethod = "POST", OnSuccess = "window.location.reload();", OnFailure = "AjaxFailed(error);" }, new { @class = "form-horizontal", role = "form", @id = "EditForm" })) {
}
使用Javascript:
function AjaxFailed(error) {
debugger
$(".ErrorBox").prop('hidden', false);
$('.ModalErrorText').text("An error occured, please review the data and try again.");
}
我会认为BeginForm会捕获我返回的错误并将其传递给Javascript,但事实并非如此。任何人都可以帮我回复错误消息给我Javascript?
由于
答案 0 :(得分:0)
我只使用了onSuccess并删除了StatusCode
和onFailure
。希望它也有效!
public async Task<JsonResult> Edit(UserViewModel model) {
if(success)
return Json(new { votes = "Success" }, JsonRequestBehavior.AllowGet);
else
return Json(new { error = "Broken" });
}
<强>脚本强>
function onSuccess(result) {
if (result.error) {
alert(result.error); //do error
}
else {
alert(result.votes); //do success
}
}