Matt Seymour
Matt Seymour

Reputation: 9395

MVC3 ajax post mutliple checkbox values to controller

Using MVC3 I am trying to accomplish the following. I have a table which has a number of values, using ajax I want to be able to select the remove checkbox (for any number of rows) which is part of the table.

The using ajax post the result to the controller for processing. The issue I currently have is I cannot get the controller to accept the data coming from the ajax post.

I am making use of jQuery and json to make the ajax call.

function removeRooms() {
    var jdata = { 'mRooms': [] };
    $('input:checked').each(function () {
        jdata['mRooms'].push($(this).val());        })

    $.ajax({
        url: "/room/removeselectedroom/@Model.mRoomid",
        type: "POST",
        dataType: "json",
        data: jdata,
        success: function (msg) {
            $('#mRooms').html(msg);
        }
    })
}

Any help you can give or resources would be appreciated.

EDIT:: One extra thing. I am getting through a IEnumerable object but there is a parameter an item in position one of the list with the value 'on' strange as there is only numbers in my checkboxes.

Upvotes: 2

Views: 5116

Answers (1)

DanielB
DanielB

Reputation: 20210

Try to serialize the data with traditional: true

$.ajax({
    url: "/room/removeselectedroom/@Model.mRoomid",
    type: "POST",
    dataType: "json",
    data: jdata,
    traditional: true,
    success: function (msg) {
        $('#mRooms').html(msg);
    }
})

Here some information about array serialization.

As of jQuery 1.4, the $.param() method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails. You can disable this functionality globally by setting jQuery.ajaxSettings.traditional = true;.

ASP.Net MVC model binding requires array data in form of

mRooms=1&mRooms=2&mRooms=3

But from jQuery 1.4 it sends

mRooms[]=1&mRooms[]=2&mRooms[]=3

This is why you have to use traditional: true

Upvotes: 4

Related Questions