Razor MVC 5.2.3如何使用Ajax发布调用OnFailure [英] Razor MVC 5.2.3 how to call OnFailure with ajax post

查看:66
本文介绍了Razor MVC 5.2.3如何使用Ajax发布调用OnFailure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Ajax表单,我想在其中调用两个不同的javascript函数,一个用于成功,一个用于失败.在这两个调用中,我将数据从服务器传递回javascript .请注意以下几点:

I have a ajax form in which I would like to call two different javascript functions, one for success and one for failure. In both of these calls, I pass data back from the server to the javascript. Please note the following:

我认为这是

@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
}

返回帖子时,我的控制器具有以下逻辑.

My controller has the following logic when return the post.

    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的正确方法是什么?

No matter what is returned, OnSuccess is the only one that gets called. What is the proper way to call OnFailure?

推荐答案

在Rion Williams的帮助下,我能够调用这两个函数.更重要的是,我弄清楚了成功/失败后如何访问和显示所需的消息:

With the help from Rion Williams post, I was able to call both functions. More importantly, I figured out how to access and display the desired message upon success/failure:

我的控制器

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
}

这篇关于Razor MVC 5.2.3如何使用Ajax发布调用OnFailure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆