控制器动作方法返回字符串或使用ajax发布请求重定向到另一个动作 [英] Controller Action method return string or Redirect to another action with ajax post request

查看:117
本文介绍了控制器动作方法返回字符串或使用ajax发布请求重定向到另一个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过jquery ajax post调用MVC操作方法.该操作方法将返回字符串值,或者如果操作方法中的某些条件为true,则它将重定向到另一个操作方法.问题是,每当我尝试重定向到另一个动作方法时,ajax帖子都将执行错误块,并且每当动作方法返回字符串值时,它就可以正常工作.我不想使用html表单发布.下面是我的代码:

I am calling MVC action method through jquery ajax post. This action method will either return a string value or if certain condition in action method is true it will redirect to another action method. The problem is whenever i am trying to redirect to another action method the ajax post is executing the error block and whenever the action method is returning a string value it works fine. I don't want to use html form post. Below is my code:

 function VerifyCreds() {
    $.ajax({
        type: "POST",
        url: "/Login/Verify",
        data: '{Username: "' + $("#txtUsername").val() + '",Password: "' + $("#txtPassword").val() + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            alert(response);
        },
        failure: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

public ActionResult Verify(string Username, string Password)
    {
        string Response = "0";
        EmployeeEntities ent = new EmployeeEntities();
        var val = ent.VerifyUser(Username, Password);
        Response = val.FirstOrDefault().ToString();
        if (Response == "1")
        {
            return this.RedirectToAction("LandingPage");
        }
        return Content(Response);
    }
    public ActionResult LandingPage()
    {
        return View();
    }

推荐答案

您正在明确指定json作为数据类型.这意味着,您的ajax方法期望来自服务器的响应为json字符串. jQuery ajax方法将使用JSON.parse方法从此json字符串创建JavaScript对象,并将其传递给回调.当您从服务器进行重定向时,它不会返回200 OK响应,但是返回302重定向响应,浏览器通常会重新调用响应的位置标头值.由于服务器返回的字符串无法使用JSON.parse安全地转换为JavaScript对象,因此您将获得ajax方法的错误回调. (我的猜测是对LandingPage调用的响应!.检查网络"标签以查看响应是什么)

You are explicitly specifying json as the data type. that means, your ajax method expects the response from the server as a json string. The jQuery ajax method will use JSON.parse method to create a JavaScript object from this json string and pass it to the callback. When you do a redirect from server, it is not returning a 200 OK response back, but a 302 redirect response back and browser will usually makes a new call to the location header value of the response. You are getting the error callback of the ajax method because the server is returning some string which cannot be safely converted to a JavaScript object using JSON.parse. (My guess is that the response for the LandingPage call!. Check the network tab to see what response is coming)

如果您绝对想处理这种情况,则最好在两种情况下都返回正确的JSON结构,并在客户端检查此JSON数据并根据需要进行重定向.

If you absolutely want to handle this situation, you may better return a proper JSON structure in both the cases and inspect this json data at client side and do a redirect as needed.

我还建议您使用适当的类型.使用int而不是将数字存储在string变量中.

I also suggest you to use the appropriate types. Use int instead of storing a number in a string variable.

public ActionResult Verify(string Username, string Password)
{       
    var ent = new EmployeeEntities();
    var val = ent.VerifyUser(Username, Password);
    var response = val.FirstOrDefault();
    if (response == 1)
    {
       return Json(new { status="redirect", url = Url.Action("LandingPage")});      
    }
    return Json(new { status="success", message = "Valid login" });
}

并在您的ajax调用成功的情况下,检查此json数据并基于status属性,进行重定向或向用户显示消息.

and in the success event of your ajax call, inspect this json data and based on the status property, do a redirect or show a message to the user.

success: function (response) {
            if(response.status==="redirect")
            {
                window.location.href = response.url;
            }
            else
            {
                alert(response.message);
            }
        },

您还可以从ajax调用中完全删除dataType: "json",. jQuery将根据响应标头智能地猜测类型并使用它.由于我们从操作方法中显式返回了Json,因此响应Content-Type标头值将为application/json

You can also totally remove dataType: "json", from your ajax call. jQuery will intelligently guess the type based on the response headers and use that. Since we are explicitly returning Json from our action method, the response Content-Type header value will be application/json

这篇关于控制器动作方法返回字符串或使用ajax发布请求重定向到另一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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