0

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?

1 Answer 1

3

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.

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

Comments

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.