首页 新闻 会员 周边

mvc中使用ajax传递json数组老是失败。

0
悬赏园豆:60 [已解决问题] 解决于 2012-06-07 00:31
    function updateItemsQtys() {
        var postData;
        var postArr = [];
        var index = 0;
        
        $("#[id^='Qty-']").each(function () {
            itemElementId = $(this).attr('id');
            var productId = 0;
            productId = itemElementId.replace("Qty-", "");
            
            postArr[index] = { ProductId: productId, Qty: $(this).val() };
            index++;
        });
        
        postData = { Items: postArr };
        
        var jsonData = JSON.stringify(postData);
        alert(jsonData);
        //$.post('@Html.Resolve("Basket/UpdateItems")', jsonData, updateBasket, "json");
        $.ajax({
            url: '@Html.Resolve("Basket/UpdateItems")',
            type: 'POST',
            data: jsonData,
            dataType: 'json',
            contentType: 'application/json',
            success: updateBasket
        });
    }

这是js代码,传递的json数据基本上是这样的:

{"Items" : "[{"ProductId" : "4", "Qty" : "5"}, {"ProductId" : "2", "Qty" : "2"}]"}

c#解析json数据的代码:

    public class JsonModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");
            if (bindingContext == null)
                throw new ArgumentNullException("bindingContext");

            var serializer = new DataContractJsonSerializer(bindingContext.ModelType);

            return serializer.ReadObject(controllerContext.HttpContext.Request.InputStream);
        }
    }

把json解析成的类型:

    [DataContract]
    [ModelBinder(typeof(JsonModelBinder))]
    public class JsonBasketQtyUpdateRequest
    {
        [DataMember]
        public JsonBasketItemUpdateRequest[] Items { get; set; }
    }

    [DataContract]
    [ModelBinder(typeof(JsonModelBinder))]
    public class JsonBasketItemUpdateRequest
    {
        [DataMember]
        public int ProductId { get; set; }
        [DataMember]
        public int Qty { get; set; }
    }

提交到action的定义:

        [HttpPost]
        public JsonResult UpdateItems(JsonBasketQtyUpdateRequest jsonBasketQtyUpdateRequest)

不明白为什么老是解析失败,提示错误:应为来自命名空间“”的元素“root”。。遇到名称为“”、命名空间为“”的“None”。

问题补充:

现在发现原来是JsonModelBinder中的controllerContext.HttpContext.Current.Request.InputStream读入得数据为空。。但不知道为什么为空。。。

浩GE的主页 浩GE | 初学一级 | 园豆:105
提问于:2012-06-06 17:05
< >
分享
最佳答案
1

貌似JSON的格式有点问题,应该是这样写吧

{"Items" : [{"ProductId" : "4", "Qty" : "5"}, {"ProductId" : "2", "Qty" : "2"}]}

收获园豆:40
psforever | 菜鸟二级 |园豆:461 | 2012-06-06 23:34
其他回答(4)
0

JSON部分只传 

[{"ProductId" : "4", "Qty" : "5"}, {"ProductId" : "2", "Qty" : "2"}]

试试

收获园豆:10
artwl | 园豆:16736 (专家六级) | 2012-06-06 17:16

还是不行,同样的错误

支持(0) 反对(0) 浩GE | 园豆:105 (初学一级) | 2012-06-06 18:50
0

使用FIDDLER2跟踪下传递的数据内容。

收获园豆:10
无之无 | 园豆:5095 (大侠五级) | 2012-06-06 17:41

传递的数据内容就是{"Items" : "[{"ProductId" : "4", "Qty" : "5"}, {"ProductId" : "2", "Qty" : "2"}]"},基本上就是这样了

支持(0) 反对(0) 浩GE | 园豆:105 (初学一级) | 2012-06-06 19:09

@浩GE: 其实不用那么麻烦的,直接传递你这个json字符串,MVC就会自动解析的。

在Basket/UpdateItems的这个方法中这样使用, public ActionResult UpdataItems(List<Product> items){}

在前台传递时,$.ajax()方法中需要把traditional设置为 true   , traditional的作用和  JSON.stringify(postData)的作用是一样的。traditional,目的是为了得到:
Values=1&Values=2&Values=3;否则的话,将会得到:
Values[]=1&Values[]=2&Values[]=3
那么MVC就不认识了。

支持(0) 反对(0) Zigzag | 园豆:70 (初学一级) | 2012-07-09 09:43
1

坑爹的,我特意试了一下你这个代码。

发现JSON格式没有问题,后来还尝试了换一种序列化方式也没有问题,

问题在[ModelBinder(typeof(JsonModelBinder))]这句,你把2个都去掉以后试试。时间太晚了,没仔细查为什么。

我测试的Json是这个{"Items":[{"ProductId":1,"Qty":2},{"ProductId":3,"Qty":4},{"ProductId":5,"Qty":6}]}

简化了你的jQuery代码,直接提交了上面的Json。

wjn2010 | 园豆:202 (菜鸟二级) | 2012-06-07 02:11

非常感谢!不过的确是出错在json格式上,因为我的页面上的一个js文件和json2.js有冲突,导致JSON.stringify函数格式化数组的时候多了2个引号,我把那个js文件去了就没问题了。

支持(0) 反对(0) 浩GE | 园豆:105 (初学一级) | 2012-06-07 12:15
0

_April | 园豆:204 (菜鸟二级) | 2013-08-07 23:20
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册