0

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>"
        }
    })
2
  • Show us how you are constructing selectedID? Commented Jan 22, 2016 at 10:51
  • @ramiramilu var selectedID = $("select#messages").val(); Commented Jan 22, 2016 at 10:54

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

However this should be a get operation, is it alright to use a POST?
I would suggest use POST to pass more complex data (strongly typed data), and use GET for simple parameters and normal querystrings like strings and insensitive data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.