c# - 将 JSON 对象传递给 MVC

标签 c# json ajax asp.net-mvc model-binding

我有一个简单的问题,需要很长时间才能弄清楚。我似乎无法从 JS 获取数据到 MVC。

JS:

           var stuff = [{a: 1, b: "Low"}, {a: 5, b:"High"}];
           $.ajax({
                url: '@Url.Action("Action")',
                type: 'POST',
                data: JSON.stringify({ stuff: stuff }),
                traditional: true
            });
            

MVC

         public enum Level
         {
              High = 10,
              Normal = 5,
              Low = 1
         }
         ...
         public class MyModel
         {
              public int a { get; set; }
              public Level b { get; set; }
         }
         ...
         public ActionResult Action(List<MyModel> stuff){
              //stuff is always null no matte what I try?
              ....
         }

我不确定我的问题到底出在哪里,因为这很难调试。

最佳答案

在您的 ajax 调用中指定 contentType 属性,它应该可以正常工作。

当使用 $.ajax 向服务器发送数据时,默认的 contentType 值为 "application/x-www-form-urlencoded; charset=UTF-8"。由于我们发送的是 JSON 数据,因此我们应该指定它。

var stuff = [{a: 1, b: "Low"}, {a: 5, b:"High"}];

$.ajax({
    url: '@Url.Action("Action")',
    type: 'POST',
    data: JSON.stringify({ stuff: stuff }),

    contentType:"application/json",  //This is the new line

    traditional: true
}).done(function(res) {
    console.log("Result came back");
});

关于c# - 将 JSON 对象传递给 MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33807459/

相关文章:

javascript - 当类在表单提交中相同时,按钮和跨度有什么区别。?

jquery - 使用 Pyramid 处理 ajax 文件上传服务器端

javascript - 将 Json 从 Angular 发送到 php 文件

javascript - 无法在 ajax 调用中创建 window.location.reload()

c# - 如何为面向 net45 的类库(包)项目运行 xunit 测试?

c# - TextRenderer.DrawText 在 XP 和 Vista 上以不同方式呈现 Arial

c# - 使用 Mono.Cecil 将索引器添加到 TypeDefinition

c# - RadGrid 中的 ComboBox

javascript - "reset"对象的属性顺序如何? JSON.stringify() 保留它们

ios - 解析字典的 JSON 数组