user1938460
user1938460

Reputation: 75

Pass Data string using ajax to controller method

I am creating a filter list. I have a several multi-select lists where the user can choose several options. The problem is I am using ajax to return the values and call a controller method which will return a Json data which will then be displayed on the website. But the problem is it doesn't work.

Controller Method:

[HttpPost]
public ActionResult FilterData(string a, string b, string c, string d){
  //Do Something with the strings e.g. filter the data.
  return Json(result, JsonRequestBehavior.AllowGet);
}

Ajax Method for getting filtered data:

$(document).ready(function() {
$("#submitBTN").click(function() {
var ab = $('#selectedID1').val();
var bc = $('#selectedID2').val();
var cd = $('#selectedID3').val();
var de = $('#selectedID4').val();

$.ajax({
       contentType: "application/json; charset=utf-8",
       url:"/Controller/FilterData",
       type: "POST",
       data: JSON.stringify({a: ab, b: bc, c: cd, d:de }),
       success: function(result){

       } 
       error: function(){}
     });
       return false;
      });
   });

Using firebug I can see the right values are posted. And I know that if I manually select string a via the url link it get the correct filtered data. However, this data does not seem to get into the method and output all the data without being filtered using the postes values.

The problem is that the Data Posted is not being pciked up or sent to the method FilterData, so it returns all the data as it should do if there are no filter options selected. I would like to know how I can fix the code so I can get the data posted by ajax to send that data to method FilterData parameters e.g. string a, string b, string c and string d.

Upvotes: 2

Views: 16386

Answers (2)

Nenad
Nenad

Reputation: 26647

Update: Now when you restated problem, here is the line that had issue (you were using JSON.stringify on data value):

data: { a: ab, b: bc, c: cd, d: de }

You were converting data into 1 JSON string, which is not what MVC expects.

"{"a":1,"b":2,"c":3,"d":4}"

Instead it expects key value pairs (normal post-back format):

a=1&b=2&c=3&d=4

So now full example without typos:

$(document).ready(function () {
    $("#submitBTN").click(function(){
        var ab = $('#selectedID1').val();
        var bc = $('#selectedID2').val();
        var cd = $('#selectedID3').val();
        var de = $('#selectedID4').val();

        $.ajax({
            url: '/MyController/FilterData',
            type: 'POST',
            data: { a: ab, b: bc, c: cd, d: de },
            success: function(result) {

            },
            error: function() {
            }
        });
    });
});

You don't need JsonRequestBehavior.AllowGet if it's just POST request (although it doesn't break anything).

Upvotes: 1

Daniele
Daniele

Reputation: 1938

try with:

url:'/Controller/FilterData',

Upvotes: 0

Related Questions