Eyal Eyal - 5 months ago 26
Javascript Question

Send Array of Objects from JavaScript to C# controller

I was trying several ways to pass the list of objects to the controller but
the controller always receives

null


Here is my code:

View:

$('#btnSave').click(function () {

var arrPropIdPos = new Array();

$('.property').each(function () {
var obj = {
PropertyId : $(this).attr('PropertyId'),
Xposition : $(this).attr('xPos'),
Yposition : $(this).attr('yPos')

};
arrPropIdPos.push(obj);
});

var jsonData = JSON.stringify(arrPropIdPos);


$.ajax({
url: "/PropertyPosition/Insert/",
type: 'POST',
data: jsonData,
dataType: 'json',
//...
},


console.log(arrPropIdPos);

0: Object
PropertyId: "1"
Xposition: "11"
Yposition: "55"
__proto__: Object

1: Object
PropertyId: "2"
Xposition: "651"
Yposition: "48"
__proto__: Object


console.log(jsonData);

[{"PropertyId":"1","Xposition":"11","Yposition":"55"},
{"PropertyId":"2","Xposition":"651","Yposition":"48"}]


Controller (option 1):

[HttpPost]
public JsonResult Insert(string jsonData)
{
// jsonData is null
}


Controller (option 2):

public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}

public JsonResult Insert(List<PropertyPositionInsert> model)
{
// model is null
}

Answer
 $('#btnSave').click(function () {

    var arrPropIdPos = new Array();

    $('.property').each(function () {

        var obj = {
             'PropertyId' : $(this).attr('PropertyId')
            ,'Xposition' : $(this).attr('xPos')
            ,'Yposition' : $(this).attr('yPos')

        };

        arrPropIdPos.push(obj);
    });    
    $.ajax({
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify(arrPropIdPos),
            url: "/PropertyPosition/Insert/"                                    
        });

Class:

  public class PropertyPositionInsert
    {
        public string PropertyId { get; set; }
        public string Xposition { get; set; }
        public string Yposition { get; set; }

    }

Controller:

 public JsonResult Insert(PropertyPositionInsert[] model)
    {
    }