Passing a list of objects to an MVC controller using jQuery Ajax

I am trying to pass an array of objects to an MVC controller method using the jQuery ajax () Function. When I enter the PassThing () controller method of C #, the argument to β€œstuff” is null. I tried this using the List for type argument, but this does not work either. What am I doing wrong?

<script type="text/javascript"> $(document).ready(function () { var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Xhr/ThingController/PassThing', data: JSON.stringify(things) }); }); </script> public class ThingController : Controller { public void PassThing(Thing[] things) { // do stuff with things here... } public class Thing { public int id { get; set; } public string color { get; set; } } } 
+105
jquery c # asp.net-mvc
Nov 06
source share
10 answers

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

 $(document).ready(function () { var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; things = JSON.stringify({ 'things': things }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Home/PassThings', data: things, success: function () { $('#result').html('"PassThings()" successfully called.'); }, failure: function (response) { $('#result').html(response); } }); }); public void PassThings(List<Thing> things) { var t = things; } public class Thing { public int Id { get; set; } public string Color { get; set; } } 

From this I learned two things: 1) The parameters contentType and dataType are absolutely necessary in the ajax () function. This will not work if they are missing. I found this after much trial and error. 2) To pass an array of objects to the method of the MVC controller, simply use the JSON.stringify ({'things': things}) format.

I hope this helps someone else!

+168
Nov 06 '12 at 16:38
source share

Could you just do it?

 var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; $.post('@Url.Action("PassThings")', { things: things }, function () { $('#result').html('"PassThings()" successfully called.'); }); 

... and mark your action with

 [HttpPost] public void PassThings(IEnumerable<Thing> things) { // do stuff with things here... } 
+29
Mar 26 '15 at 16:28
source share

Formatting data that may be a problem. Try one of the following:

 data: '{ "things":' + JSON.stringify(things) + '}', 

Or (from How to send an array of strings to ASP.NET MVC Controller without a form? )

 var postData = { things: things }; ... data = postData 
+12
Nov 06
source share

I have an excellent answer for all this: I tried so many solutions that could not get, finally I was able to manage, please find the detailed answer below:

  $.ajax({ traditional: true, url: "/Conroller/MethodTest", type: "POST", contentType: "application/json; charset=utf-8", data:JSON.stringify( [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]), success: function (data) { $scope.DisplayError(data.requestStatus); } }); 

Controler

 public class Thing { public int id { get; set; } public string color { get; set; } } public JsonResult MethodTest(IEnumerable<Thing> datav) { //now datav is having all your values } 
+7
Jul 27 '15 at 14:42
source share

The only way to get this to work is to pass JSON as a string, and then deserialize it using JavaScriptSerializer.Deserialize<T>(string input) , which is pretty strange if this is the default deserializer for MVC 4.

My model has nested object lists, and the best I can get using JSON data is the top-most list, which has the correct number of elements, but all the fields in the elements were empty.

It shouldn't be that hard.

  $.ajax({ type: 'POST', url: '/Agri/Map/SaveSelfValuation', data: { json: JSON.stringify(model) }, dataType: 'text', success: function (data) { [HttpPost] public JsonResult DoSomething(string json) { var model = new JavaScriptSerializer().Deserialize<Valuation>(json); 
+7
Jul 19 '17 at 4:50
source share

This is the working code for your request, you can use it.

Controler

  [HttpPost] public ActionResult save(List<ListName> listObject) { //operation return Json(new { istObject }, JsonRequestBehavior.AllowGet); } } 

Javascript

  $("#btnSubmit").click(function () { var myColumnDefs = []; $('input[type=checkbox]').each(function () { if (this.checked) { myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') }) } else { myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') }) } }); var data1 = { 'listObject': myColumnDefs}; var data = JSON.stringify(data1) $.ajax({ type: 'post', url: '/Controller/action', data:data , contentType: 'application/json; charset=utf-8', success: function (response) { //do your actions }, error: function (response) { alert("error occured"); } }); 
+4
Mar 02 '17 at 13:55 on
source share
  var List = @Html.Raw(Json.Encode(Model)); $.ajax({ type: 'post', url: '/Controller/action', data:JSON.stringify({ 'item': List}), contentType: 'application/json; charset=utf-8', success: function (response) { //do your actions }, error: function (response) { alert("error occured"); } }); 
+1
Jan 04 '17 at 9:32 on
source share

If you are using the ASP.NET Web API, you just need to pass data: JSON.stringify(things) .

And your controller should look something like this:

 public class PassThingsController : ApiController { public HttpResponseMessage Post(List<Thing> things) { // code } } 
0
Dec 25 '15 at 10:07
source share

Modification from @veeresh i

  var data=[ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; //parameter var para={}; para.datav=data; //datav from View $.ajax({ traditional: true, url: "/Conroller/MethodTest", type: "POST", contentType: "application/json; charset=utf-8", data:para, success: function (data) { $scope.DisplayError(data.requestStatus); } }); In MVC public class Thing { public int id { get; set; } public string color { get; set; } } public JsonResult MethodTest(IEnumerable<Thing> datav) { //now datav is having all your values } 
0
Apr 24 '17 at 7:56 on
source share

Ends your list of objects with another object containing a property that matches the parameter name expected by the MVC. An important bit is the wrapper around the list of objects.

 $(document).ready(function () { var employeeList = [ { id: 1, name: 'Bob' }, { id: 2, name: 'John' }, { id: 3, name: 'Tom' } ]; var Employees = { EmployeeList: employeeList } $.ajax({ dataType: 'json', type: 'POST', url: '/Employees/Process', data: Employees, success: function () { $('#InfoPanel').html('It worked!'); }, failure: function (response) { $('#InfoPanel').html(response); } }); }); public void Process(List<Employee> EmployeeList) { var emps = EmployeeList; } public class Employee { public int Id { get; set; } public string Name { get; set; } } 
0
Sep 21 '17 at 22:06
source share



All Articles