BKahuna
BKahuna

Reputation: 611

MVC 3 Controller not recognizing JSON passed back by jQuery AJAX

I have an MVC 3 app that is using jQuery AJAX to fire off a controller action to return a partial view.

The client side code:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        data: '{searchString:"' + searchCriteria + '"}',
        success: function (result) {
            $("#customerTabBody").html(result);
        }
    });
};

The Controller code:

[HttpPost]
public ActionResult GetCustomerList(string searchString)
{
    var custService = new CustomerViewModels();
    var custListVM = custService.GetSearchList(searchString);

    return PartialView("GetCustomerList", custListVM);
}

When I fire the client side jQuery I can see via Firebug that the searchString is being sent and appears properly formatted. Here's what Firebug shows as the post message:

{searchString:'ar'}

and Firebug is able to properly parse the JSON. If I put a breakpoint in the controller code and test the value of the searchString parameter is is NULL. However if I just hardcode the JSON:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        data: {searchString:'ar'},
        success: function (result) {
            $("#customerTabBody").html(result);
        }
    });
};

It works perfectly and the controller parameter is correctly populated.

What am I doing wrong such that when I parametrize my JSON string it fails?

Thanks

Upvotes: 1

Views: 768

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039428

Try like this:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        data: { searchString: searchCriteria },
        success: function (result) {
            $('#customerTabBody').html(result);
        }
    });
}

This will ensure that the data sent to the controller is properly URL encoded. Also you haven't shown how/where you are calling this getCustomerList function but if it is on the click of some anchor or button make sure that you are cancelling the default action as well.

Upvotes: 1

Related Questions