Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass this js array to my MVC 3 controller?

I am getting null values in the controller. Not sure what am I am missing.

I have a grid where I have a list of guests (with name & email) where user select guest by checkbox.

Then I read name and emails of the selected contacts and build js array. Then this array is passed to MVC 3 controller.

JS code:

var name ='', email='';
    var guest = new Array();
            var guests = new Array();
            $('.CBC').each(function () {  //loop grid by checkbox class
                if (this.checked) {
                    name = GetSelectedName();
                    email = GetSelectedEmail();
                    guest = { 'Email': email, 'Name': name };
                    guests.push(guest);
                }
            });

        $.ajax({
        type: "POST",
        url: GetURL(),
        data: guests,
        dataType: "json",
        success: function (res) {
           //do something
        }
});

Controller:

[HttpPost]
    public ActionResult AddGuests(List<SelectedGuest> guests)
    {            
        GuestService svc = new GuestService();
        //do something with guests
        //But Name and Email of all items in guests are null!!!
    }

public class SelectedGuest
{
    //represent the email columns of the contact grid
    public string Email { get; set; }

    //represent the Name column of the contact grid
    public string Name { get; set; }
}

Do I need to explicitly convert js array to json object to serialize it?

like image 837
kheya Avatar asked Jun 13 '11 05:06

kheya


1 Answers

$.ajax({
            type: "POST",
            url: "yourUrl",
            data: JSON.stringify(yourArray),
            contentType: "application/json; charset=utf-8"
        });

contentType: "application/json; charset=utf-8" - is very important part

[HttpPost]
public void Fake(List<yourType> yourArray)
{
}
like image 124
13_Shark Avatar answered Oct 20 '22 02:10

13_Shark