jQuery 如何将此 js 数组传递给我的 MVC 3 控制器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6327019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:41:53  来源:igfitidea点击:

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

jqueryajaxjsonasp.net-mvc-3

提问by kheya

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

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 对象来序列化它?

回答by 13_Shark

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

回答by Tx3

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

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

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

回答by Alex R.

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

回答by Amin Saqi

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

回答by Mohammad Imran

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

只需在 ajax 中设置“traditional:true”即可

Example:

示例

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

回答by hakuna

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

斯里尼瓦斯

回答by Kywillis

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.

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