1

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

1 Answer 1

1

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.

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

2 Comments

Folks - We have a winner! Thanks Darin
Weird that StackOverflow makes you wait about 12 minutes before you can mark an answer as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.