Mike
Mike

Reputation: 2339

ajax not passing array to controller

I am trying to pass the ids of the checked boxes to the controller using ajax. Here is the jquery:

function compareEvents() {
        var selected = new Array();
        $('input:checked').each(function () {
            selected.push($(this).attr('id'));
            alert("Event " + $(this).attr('id') + " will be compared");
        });

        $.ajax({
            url: "/Event/CompareEvents",
            contentType: "application/x-www-form-urlencoded",
            type: "POST",
            datatype: "json",
            data: JSON.stringify({eventIds:selected}),
            error: function (xmlHttpRequest, errorText, thrownError) {
                alert(xmlHttpRequest, errorText, thrownError);
            },
            success: function (data) {
                alert("success");
                document.location = data;
            }
        });

The alert successfully returns the ids of the checked checkboxes. And returns a success message upon completion.

Here is the controller method:

    [HttpPost]
    public ActionResult CompareEvents(List<int> eventIds)
    {
        return null;
    }

This gets called successfully, except when i debug, eventIds is returning null. Can anyone see why eventIds is not getting the correct values?

Upvotes: 0

Views: 3840

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You are sending JSON:

data: JSON.stringify({ eventIds:selected }),

and setting the contentType header to "application/x-www-form-urlencoded".

Be consistent with what you are sending:

contentType: "application/json",

Also there's no such setting called datatype. The actual setting is dataType but it is redundant because if your controller action is setting the Content-Type response header to application/json (which it normally should if you are returning a JsonResult), jQuery is intelligent enough to use this header and process the response from the server and pass an already parsed object to your success callback.

Upvotes: 3

Related Questions