简体   繁体   中英

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 tryed IEnumberable when sending the list of objects as JSON the varible 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!

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

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