我有一个 Web Api,其中包含此代码
@{
AjaxOptions addAjaxOpts = new AjaxOptions
{
// options will go here
OnSuccess = "getData",
OnFailure="selectView('add')",
HttpMethod = "Post",
Url = "/api/AccountManage/CreateAccount"
};
}
在 Controller 中:
[HttpPost]
public void CreateAccount(CollaborateurModel item)
{
try{}
catch{
// return failure
}
}
我需要实现failure部分
来执行OnFailure
方法。
那么我怎样才能完成这个任务呢?
最佳答案
您可以从使用 Json 结果 ( MSDN ref. ) 开始
片段示例:
[HttpPost]
public ActionResult CreateAccount(CollaborateurModel item)()
{
try{
//do operations that may fail
var response = new { Success = true};
return Json(response );
}catch{
var errorResponse= new { Success = false, ErrorMessage = "error"};
return Json(errorResponse);
}
}
然后在客户端使用 JQuery 调用 Controller :
$(function () {
$(".test-link").click(function (e) {
$.post("controllerName/CreateAccount", function (data) {
if (data.Success == true) {
alert("Success");
}
else {alert(data.ErrorMessage);}
});
return false;
}).fail(function() {
alert( "error" );
});
});
Jquery 上的失败函数将处理客户端与服务器之间可能存在的通信问题。
更多关于JQuery的信息你可以找到here .
关于javascript - 在 webApi Controller 中实现 Onfailure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720187/