Cannot figure out why I pass an array of JavaScript objects to controller method that the controller method isn't getting the object

I been looking around for awhile now and have came across this question many times and I am doing the same thing that are in the solutions but baffled why its not working. I'm sure this question will be marked as a duplicate, and it is, but I am missing something.

Here is the array of JavaScript objects

var gridData = {
    tempData: [
        { UserName: "Tom", LastName: "Solomon" },
        { UserName: "Harry", LastName: "Solomon" },
        { UserName: "Sally", LastName: "Solomon" },
        { UserName: "Dick", LastName: "Solomon" },
    ]
};

Here is my Ajax

function TossIt() {
    var sendThis = gridData.tempData;
    console.log(sendThis);
    $.ajax({
        type: "POST",
        url: "/Junk/JAT?s=" + sendThis,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(sendThis),
        success: function (data, textStatus, jqXHR) { },
        complete: function (e) {
        }
    })
}

Here is the method I am passing it to

[HttpPost]
public List<Stuff> JAT(Stuff s)
{
    List<Stuff> result = new List<Stuff>();


    return result;
}

and here is the class

public class Stuff
    {
        public string UserName { get; set; }
        public string LastName { get; set; }
    }

I have a break point on the JAT method and s is always null

EDIT I need to manipulate some of the properties in objects then return the list

Answers 1

  • The answer above using POST is the way to go. However, if you want to do GET and queryStrings, you can as well.

    Trivial example:

    • Client side (see $.param())

      var gridData = {
          tempData: [
              { UserName: "Tom", LastName: "Solomon" },
              { UserName: "Harry", LastName: "Solomon" },
              { UserName: "Sally", LastName: "Solomon" },
              { UserName: "Dick", LastName: "Solomon" },
          ]
      };
      
      function TossIt() {
          var sendThis = gridData.tempData;
          console.log(sendThis);
          $.ajax({
              type: "GET",
              url: "/JAT?" + $.param(gridData), //using $.param() here for query string            
              success: function(data, textStatus, jqXHR) {},
              complete: function(e) {
              }
          });
      }
      
    • Controller side

      • follow the above comments/answer regarding List<Stuff>
      • HttpGet Attribute
      • Adjust the parameter name to tempData (re: $.param())

        [System.Web.Mvc.HttpGet]
        public List<Stuff> JAT(List<Stuff> tempData)
        {
           ......
        }
        

    Hth...


Related Articles