ajax 将数组从 javascript 传递到控制器 MVC 4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18112599/
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
passing array from javascript to controller MVC 4
提问by laitha0
I am using razor and I'm having a hard time passing an array to a controller. the array contains objects that I made and I am trying to do this:
我正在使用剃刀,但很难将数组传递给控制器。该数组包含我制作的对象,我正在尝试这样做:
$.ajax({
type: "POST",
url: "HomePage/HandleOperations",
data: JSON.stringify(operationCollection),
success: function (data) { alert("SUCESS");},
dataType: "json",
contentType: "application/json"
});
and my controller is:
我的控制器是:
public void HandleOperations(List<string> operationCollection)
{
}
I am not required to use ajax but I am not sure how else it could be done. In the controller it shows that the "operationCollection" contains elements but they are all null.
我不需要使用 ajax,但我不知道还能怎么做。在控制器中,它显示“operationCollection”包含元素,但它们都为空。
回答by Nalan Madheswaran
the Ajax parameter
Ajax 参数
traditional : true
will do the trick.
会做的伎俩。
回答by puddinman13
Usage of the traditional: true parameter for an ajax call:
ajax 调用的传统:true 参数的用法:
To help radbyx, using the "traditional: true" property of an ajax call, like the following, will tell ajax to use the traditional form of serialization. More details: http://api.jquery.com/jQuery.param/or What is "traditional style of param serialization' in JQuery.
为了帮助 radbyx,使用 ajax 调用的“traditional: true”属性,如下所示,将告诉 ajax 使用传统的序列化形式。更多详细信息:http: //api.jquery.com/jQuery.param/或JQuery 中的“参数序列化的传统风格”是什么。
$.ajax({
type: "POST",
url: "HomePage/HandleOperations",
data: {operations: operationCollection},
traditional: true,
success: function (data) { alert("SUCCESS"); }
});
回答by Anders Lindén
Client side:
客户端:
$.ajax({
type: "POST",
url: "HomePage/HandleOperations",
data: {operations: operationCollection},
success: function (data) { alert("SUCCESS"); }
});
and declare a class server side like this:
并像这样声明一个类服务器端:
public class Operation
{
public int Index;
public string Source;
public string Target;
public int AddOrDel;
}
then you can have this action:
那么你可以有这个动作:
public void HandleOperations(Operation[] operations)
{
}
回答by Mohammad Imran
Add "traditional:true" parameter in your ajax.
在 ajax 中添加“traditional:true”参数。
Example:
例子:
var parentValueToPush=new Array();
$('[name=SelectedUsers]:checked').each(function () {
parentValueToPush.push($(this).val());
temp.push($(this).val());
});
$.ajax({
url: //URL,
type: 'get',
traditional: true,
dataType: 'html',
cache: false,
data: { SelectedUsers: parentValueToPush},
success: function (data) {
//Result
}
});

