将JSON对象传递给MVC

本文关键字:MVC JSON 对象 | 更新日期: 2023-09-27 18:22:34

我有一个简单的问题,需要很长时间才能解决。我似乎无法将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?
              ....
         }

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

将JSON对象传递给MVC

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

当使用$.ajax向服务器发送数据时,默认的contentType值为"a pplication/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");
});

我刚刚意识到这就是问题所在:

data: JSON.stringify({ stuff: stuff })

将其更改为:

data: JSON.stringify(stuff)