如何将这个js数组传递给MVC 3控制器?

[英]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数组。然后这个数组被传递给MVC 3控制器。

JS code:

JS代码:

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?

我是否需要显式地将js数组转换为json对象以序列化它?

7 个解决方案

#1


7  

$.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

contentType:“application / json;charset=utf-8"是非常重要的部分

[HttpPost]
public void Fake(List<yourType> yourArray)
{
}

#2


4  

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

也许将传统的设置更改为true会有所帮助。这里是我用来将惟一标识符(Guids)发布到控制器操作中的(修改过的)代码。

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

#3


3  

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

如果你有使用插件的自由,试试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
     }
);

#4


1  

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

你会得到null,因为你发送的json数组是错误的。

First, you should serialize your json array:

首先,您应该序列化json数组:

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

#5


1  

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

在ajax中设置“传统的:true”。

Example :

例子:

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

#6


0  

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.

您还可以创建自定义模型绑定器。这允许您编写从请求对象中获取原始输入并从中创建对象的代码。这会让您创建一个字符串列表或任何您想要在控制器中看到的对象。它也是非常可重用的。

#7


0  

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

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/06/13/54ce350d009b87ad8a46ca744ad5733c.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告