1

我有以下两个保存数据的类:

public class ItemList{
    public IList<Item> Items{get;set;}
}

public class Item{
    public int id {get;set}
    public string name {get;set}
}

我的控制器看起来像:

 public virtual JsonResult SaveItems(ItemList items)
    {}

我尝试像这样发布一个 JS 对象:

var toPost = { "items" : [ {"id" : 1, "name":"test}, {"id" : 1, "name":"test"}] }


   $.ajax({
                        type: "POST",
                        url: "URL TO POST TO",
                        dataType: "json",
                        data: toPost,
                        traditional: true,
                        success: function (data, status, request) {
                            if (data.Error != undefined) {
                                alert("System Error: " + data.Error);

                                return;
                            }
                            console.log("Success");

                        },
                        error: function (request, status, error) {
                            console.log("ERROR");
                        }
                    });

console.log在发布之前做了一个,数据看起来与toPost变量中描述的一样,但是在 C# 端调试时ItemList items为空

4

2 回答 2

3

在 toPost 中使用JSON.stringify并设置内容类型

$.ajax({
                    ...
                    contentType: "application/json; charset=utf-8"
                    data: JSON.stringify(toPost),
                    ...
});
于 2013-10-14T13:55:13.737 回答
0

您的 SaveItems 方法需要一个 ItemsList 对象,并且请求中发送的是一个字符串。您需要将请求数据反序列化到您的 ItemsList 对象中,如下所示:

public virtual JsonResult SaveItems(String jsonRequest)
{
    ItemsList items = Util.JsonSerializer.Deserialize<ItemsList>(jsonRequest);

    // further processing of items
}
于 2013-10-14T13:52:50.860 回答