简体   繁体   中英

Passing JSON object to MVC

I am having a simple issue which is taking way to long to figure out. I cant seem to get data from JS into 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?
              ....
         }

I am not sure where my problem actually is, as this is surprisingly hard to debug. Thanks in advanced for any help.

Specify the contentType properpty on your ajax call and it should work fine.

When sending data to server using $.ajax, default contentType value is "a pplication/x-www-form-urlencoded; charset=UTF-8 " . Since we are sending JSON data, We should specify it.

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");
});

I just realized this is the issue:

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

change it to:

data: JSON.stringify(stuff)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM