本文介绍了jQuery.parseJSON无法从MVC控制器操作用于JsonResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery.parseJSON来解析MVC3控制器操作的返回值.

I am trying to use jQuery.parseJSON to parse out the return value from an MVC3 controller action.

控制器:

    [HttpPost]
    public JsonResult LogOn(LogOnModel model, string returnUrl)
    {
        .. do stuff ..

        if (errors.Count() < 0)
        {
            return Json(new object[] { true, model, errors });

        }

        return Json(new object[] { false, model, errors });
    }

jQuery:

$.ajax({
                url: form.attr('action'),
                type: "POST",
                dataType: "json",
                data: form.serialize(),
                success: function (data) {
                    var test = jQuery.parseJSON(data);                      
                }   
            });

提琴手的杰森结果:

[false,{"UserName":"1","Password":"2","RememberMe":false},[{"Key":","Errors":[{"Exception":null ,"ErrorMessage": 提供的用户名或密码不正确.}]}]]

[false,{"UserName":"1","Password":"2","RememberMe":false},[{"Key":"","Errors":[{"Exception":null,"ErrorMessage":"The user name or password provided is incorrect."}]}]]

提琴手可以解析结果:

对jQuery.parseJSON的调用返回null.我的问题是,如何将json返回值解析为对象?

The call to jQuery.parseJSON is returning null.My questions is, how can I parse the json return value into an object?

谢谢!

推荐答案

您无需在成功处理程序中调用parseJSON,因为ajax已经解析了JSON结果(因为您指定了dataType:'json')放入您的数组.

You don't need to call parseJSON in your success handler, because ajax will have already parsed the JSON result (it does this automatically because you specified dataType:'json') into your array.

但是,我建议返回某种结果对象(无论您是使用C#创建实际的类还是使用匿名类型).

However, I'd recommend returning some sort of result object (whether you create an actual class in C# or use an anonymous type).

    [HttpPost]
    public JsonResult LogOn(LogOnModel model, string returnUrl)
    {
        .. do stuff ..

        if (errors.Count() < 0)
        {
            return Json(new { success=true, model, errors });

        }

        return Json(new { success=false, model, errors });
    }

和客户

$.ajax({
                url: form.attr('action'),
                type: "POST",
                dataType: "json",
                data: form.serialize(),
                success: function (result) {
                    alert(result.success);
                    // also have result.model and result.errors                      
                }   
            });

这篇关于jQuery.parseJSON无法从MVC控制器操作用于JsonResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:31