C# JSON 从 JavaScript 发布

标签 c# javascript json null

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

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

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

我的 Controller 看起来像:

 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 为空

最佳答案

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

$.ajax({
                    ...
                    contentType: "application/json; charset=utf-8"
                    data: JSON.stringify(toPost),
                    ...
});

关于C# JSON 从 JavaScript 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361743/

相关文章:

c# - 使用 Thinktecture IdentityServer3 进行身份验证/授权 native Android 应用程序的正确方法是什么

Javascript 代码 getElementByID 与 C# 循环

javascript - 未捕获的类型错误 : document. getElementById(...).onclick 不是函数

java - JsonMappingException 没有在应该抛出的时候抛出

python - 如何在与 dictwriter 一起使用时正确删除 python 中的回车符(换行符 ='' 没有帮助)

ruby-on-rails - JSON和carrierwave iphone问题

c# - 如何从 .cs 文件调用 JavaScript/jQuery 函数 (C#)

c# - PCL DomCompiler 可移植类库输出

c# - 存储过程看不到在同一连接中创建的临时表

javascript - 点击位置 <div> 标签