开发者

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

开发者 https://www.devze.com 2023-03-13 00:55 出处:网络
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.

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
             开发者_如何学Python   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?


$.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)
{
}


Maybe changing setting traditional to true might help. Here is (modified) code that I used to post unique identifiers (Guids) to the controller action.

var yourArray = new Array();
// TODO: fill array with ids of checked checkboxes
$('.CBC:checked').each(function () {
   yourArray.push($(this).attr('myId'));
});

var postData = {
    yourArray: yourArray
};

$.ajax({
    type: "POST",
    url: "/ctrl/ActionName",
    data: postData,
    success: function (result) {
    },
    datatype: "json",
    traditional: true
});

In the controller I have following action.

[HttpPost]
public ActionResult ActionName(List<Guid> yourArray)
{
    return View();
}


If you have the liberty of using a plugin, try jQuery-JSON:

var guests = new Array();

// push stuff into the array

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


You get null because you're sending the json array in wrong way.

First, you should serialize your json array:

$.ajax({
        // Whatever ...
        type: "POST",
        url: "yourUrl",
        data: JSON.stringify(guests),
        // Whatever ...
    });

Second, your controller should get a string:

[HttpPost]
public ActionResult ActionName(string guests)
{
    // ...
}

and finally, you should deserialize that string to the related type:

[HttpPost]
public ActionResult ActionName(string guests)
{
    // this line eserializes guests ...

    IList<GuestType> gs = 
       new JavaScriptSerializer().Deserialize<IList<GuestType>>(guests);

    // ... Do whatever with gs ...

    return View();
}


just set the 'traditional:true" in your ajax.

Example :

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


You can also create a custom model binder. This lets you write the code that takes in the raw input out of the request object and create an object from it. This would let you create a list of strings or anything else you would like to see as an object in your controller. It is also very reusable.


I tried this, its working.

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);
            }
        });

 var PostData = { guests: guests }; //if this is creating ambiguity try using something:guest //(something is //controller parameter, change your controller parameter accordingly)              

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

Cheers,

Srinivas

0

精彩评论

暂无评论...
验证码 换一张
取 消