Johnathon64
Johnathon64

Reputation: 1320

Passing Array to mvc5 action using Ajax

I am trying to pass a javascript array where the values are from a multiselect box. However I am getting a null back from the ajax get request when it hits the action. I have tried to set a breakpoint and it comes back as null. Here is my action signature

 public JsonResult GetMessages(List<string> id, string searchText)

and here is my ajax call:

$.get("Dashboard/GetMessages", $.param({ "id": JSON.stringify(selectedID), "searchText": InputSearch }, true)
        , function (result) {
        for (var item = 0; item < result.length; item++) {
            var newMessageEntry = "<tr><td>" + result[item] + "</td></tr>"
        }
    })

Upvotes: 0

Views: 72

Answers (1)

ramiramilu
ramiramilu

Reputation: 17182

To pass array data in ajax POST, use following code.

Controller Action -

 [HttpPost]
 public JsonResult GetMessages(List<string> id, string searchText)
 {
      return Json(true);
 }

And your JQuery code should be -

$.ajax({
    url:"/Home/GetMessages",
    type:"POST",
    data:JSON.stringify({ id: selectedID, searchText: InputSearch }),
    contentType:"application/json; charset=utf-8",
    success: function(result){
        console.log(result);
    }
});

When you run the application, you should get data like shown below -

enter image description here

To make GET request, use below code.

Controller action -

public JsonResult GetMessages(List<string> id, string searchText)
{
     return Json(true);
}

And JQuery code should be -

$.ajax({
    url:"/Home/GetMessages",
    type:"GET",
    data:{ id: selectedID, searchText: InputSearch },
    contentType: "application/json; charset=utf-8",
    // Make sure we have to set Traditional set to true
    traditional: true,
    success: function(result){
        console.log(result);
    }
});

And output would be -

enter image description here

Upvotes: 1

Related Questions