我有一个ajax表单,我想在其中调用两个不同的javascript函数,一个用于成功,一个用于失败。在这两个电话中,我pass data back from the server to the javascript。请注意以下事项:
我认为这是
@using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDiv",
OnSuccess = "callSuccess(data.msg)",
OnFailure = "callFailure(data.msg)",
}, new { @class = "form-inline" }))
{
... // my content
}
我的控制器在退回帖子时有以下逻辑。
public ActionResult MyAction(string myString)
{
...
// If error occurred
return Json(new { success = false, msg= "Fail" });
...
// If no errors
return Json(new { success = true, msg= "Success" });
}
无论返回什么,OnSuccess
是唯一被调用的人。拨打OnFailure
的正确方法是什么?
答案 0 :(得分:2)
在Rion Williams的帮助下,我能够调用这两个功能。更重要的是,我想出了如何在成功/失败时访问和显示所需的消息:
我的控制器
public ActionResult MyAction(string myString)
{
...
// If error occurred
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Error occurred!");
...
// If no errors
return Json(new { success = true, msg= "Success" });
}
我的观点:
@using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDiv",
OnSuccess = "callSuccess(data.msg)",
OnFailure = "callFailure(error)", // error = "Error occurred!"
}, new { @class = "form-inline" }))
{
... // my content
}
答案 1 :(得分:1)
考虑使用HTTP状态代码
您可以考虑通过返回HTTP status code对象来返回与您要触发的错误类型(即未授权,错误请求等)相对应的相应HttpStatusCodeResult
:
// If an error occurred...
if(error)
{
// Indicate your code and error message. This uses the Bad Request status (400)
return new HttpStatusCodeResult(400, "Something went wrong...");
}
处理此客户端
如果您不想这样做,可以考虑定义单个结果事件(即OnSuccess = "call(data);
),然后在该事件中检查您的success
属性以确定要执行的操作:
function call(data){
if(data.success){
callSuccess(data.msg);
}
else{
callFailure(data.msg);
}
}
答案 2 :(得分:1)
是的,它总是会调用OnSuccess。 但是你可以在onSuccess函数中检查你的成功属性。
OnSuccess : function (data)
{
if(success)
{
alert('Json Return Success')
}
else
{
alert('json Result False')
}
}
否则你必须发送错误状态,如Rion Williams提到