Dhaval Dhaval - 6 months ago 11
Javascript Question

How to post array of json object to controller method

I am using below stuff to post list of object to controller ajax post method.

jQuery stuff:

var values = [];
values.push(rowData1);
values.push(rowData2);
values.push(rowData3);

var data = JSON.stringify({
installationControls: values
});

$.ajax({
url: '/ControllerName/fin',
type: "POST",
contentType: "application/json",
data: {
data: data
},
success: function () {
console.log('success!!');
}
});


Please suggest me what is wrong..

controller method:

[HttpPost]
public JsonResult fin(object s) {
//.................
}


posted data are as follow:

installationControls":[{"syID":"1789","FullName":"Bejin Mara","Min":"5","MSG":""},{"syStudentID":"46","FullName":"Calderon Laura","MinAbsent":"7","MSG":""},{"syID":"17","FullName":"mic Mayra","Min":"5","MSG":""}]


tried by creating same object and passed to controller argument but not worked.

Answer

Your ajax settings seem correct. However, since the endpoint expects and object named 's', I changed the data:-bit to reflect this:

    $.ajax({
        url: '/ControllerName/fin',
        type: "POST",
        contentType: "application/json",
        data: { s: data },
        success: function () {
            console.log('success!!');
        }
    });

Does that help?

Edit: The controller could accept a datastructure such as this:

public class SingleListObject
{
    // Add properties to this class to match the properties held by rowData
}

public class MyModelWithList
{
    public List<SingleListObject> MyList { get; set; }

    public MyModelWithList()
    {
        MyList = new List<SingleListObject>();
    }
}

public JsonResult fin(MyModelWithList details) {
    //.................
}

Ajax:

$.ajax({
    url: '/ControllerName/fin',
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ myList: values }), // If this doesn't work, try JSON.stringify({ details: { myList: values } })
    success: function () {
        console.log('success!!');
    }
});
Comments