简体   繁体   中英

Sending JSON from View to Controller ASP.NET MVC gives null values

I have a problem with sending JSON data from MVC View to Controller, all I get to Controller is:

在此处输入图片说明

where my JSON I send in Url.Action looks like this: (I create it by my own adding array to array by .push() and then JSON.stringify )

[
   [
      {
         "isOrdered":false,
         "orderLineId":"4550",
         "comment":"",
         "orderId":"2789"
      }
   ],
   [
      {
         "isOrdered":false,
         "orderLineId":"4551",
         "comment":"",
         "orderId":"2789"
      }
   ]
]

I use JQuery ajax POST

$.ajax({
            type: "POST",
            url: "@Url.Action("SaveCheckboxesAndComments")",
            data: JSON.stringify(array),
            traditional: true,
            contentType: "application/json; charset=utf-8",
            dataType: 'json'
        });

and my controller:

public class JsonData
        {
            public bool IsOrdered { get; set; }
            public string OrderLineId { get; set; }
            public string Comment { get; set; }
            public int OrderId { get; set; }
        }

        [HttpPost]
        public async Task<ActionResult> SaveCheckboxesAndComments(List<JsonData> jsonArray)
        {...

Should I change something in my class JsonData or in JS to get values? Because somehow the "frame" is working.

Some things to try:

  1. Open up your Network tab in the dev console and check out the details of the POST request to make sure that the url is correct and that the JSON being sent is what you expect
  2. Decorate the JsonData class with a [DataContract] attribute, and each property with a [DataMember(Name = "Name")] attribute - to make sure that you don't run into issues with casing (the property names in the class are all capitalized, and your json starts with lower case for each).
  3. It looks like you have an extra set of external [ ] brackets on your generated Json. So while your action is expecting List<JsonData> jsonArray , it is being sent List<List<JsonData> jsonArray> . See how it works removing the outermost square brackets from the json being sent.

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