Search code examples
c#javascriptajaxasp.net-mvcpost

C# Saving Object List Vs Saving Object (From JSON)


I have the following WORKING code:

Class (declared objects)

public class saveRow
{
    public int proId { get; set; }
    public string proName{get;set;}
}

Controller:

[HttpPost]
public virtual JsonResult SaveRow(saveRow input)
{ /* CODE HERE */}

JavaScript Object (Been sent)

var test = {"proId" : 1, "proName" : "Test"}

JavaScript Ajax Call

 $.ajax({
       type: "POST",
       url: "URL",
       dataType: "json",
       data: test,
       traditional: true,
       success: function (data, status, request) {
           if (data.Error != undefined) {
               alert("System Error: " + data.Error);
               $(row).find('*').attr('disabled', false);
               return;
           }

       },
       error: function (request, status, error) {
           console.log("ERROR");
       }
   });

Now the problem occurs when I want to send a list of my rows rather than one at a time so i done the following:

To test i took the same object and done

var test2 = []; test2.push(test); test2.push(test);

And the object now looks like:

[{"proId" : 1, "proName" : "Test"},{"proId" : 1, "proName" : "Test"}]

My controller now looks like :

[HttpPost]
public virtual JsonResult SaveRow(List<saveRow> input)
{ /* CODE HERE */}

Also tried IEnumerable when sending the list of objects as JSON the variable input is always null.

But every time I send this list through the controller parameter "input" is always null.

Why is this?

SOLVED:

public virtual JsonResult SaveRow(saveRow[] input)

And added content type! With JSON.stringify!


Solution

  • Try this way:

    • Set a wrapper name for your list same as that of your argument name "input"
    • Set content-type
    • Remove traditional and use JSON.stringify to stringify your data.

    JS:

    var data = { "input": test2 };
    
    $.ajax({
           type: "POST",
           url: "URL",
           dataType: "json",
           contentType:"application/json; charset=utf-8", //<--Set content Type
           data: JSON.stringify(data), //Set data
           success: function (data, status, request) {
               if (data.Error != undefined) {
                   alert("System Error: " + data.Error);
                   $(row).find('*').attr('disabled', false);
                   return;
               }
    
           },
           error: function (request, status, error) {
               console.log("ERROR");
           }
       });