KatKas
KatKas

Reputation: 23

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:

enter image description here

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.

Upvotes: 1

Views: 1454

Answers (1)

Yaakov Ellis
Yaakov Ellis

Reputation: 41480

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.

Upvotes: 1

Related Questions