将jQuery数组发送回ac#String Array

我有一个需要String[]数组的C#方法,我使用$.getJSON调用将参数传递给Controller中的Method。

我正在使用已选中的复选框的值并将它们传递回Controller,但是当我使用Stringify它会放置多个值,一起当我将数组传递给它自己时,有多个条目,但接收String[]是空的。

 var array = new Array(); $('#ids:checked').each(function() { array.push($(this).val()) } var jsonText = JSON.stringify(array); // I have tried this, but to receive one entry var dataValues = { ids: jsonText, id: $('#idNumber').val(), orderId: $('#orderId').val() }; $.getJSON("/path/to/method", dataValues, function(){}); 
 public ActionResult doSomething(String[] ids, Int32 Id, Int32 OrderId) { //do something here } 

谢谢您的帮助。

您正在将ids的值设置为JSON字符串; 但是,服务器无法知道这一点。 就服务器所知, ids是一个string值,不能转换为string[]

您应该将整个数据对象转换为JSON并指定其内容类型,而不是将一个值转换为JSON:

 var dataValues = { ids: array, //the Javascript array, *not* the JSON string id: $('#idNumber').val(), orderId: $('#orderId').val() }; $.ajax({ url: "/path/to/method", data: JSON.stringify(dataValues), success: function(){}, contentType: "application/json" }); 

我以前没有使用GET发回Arrays,我通常使用POST,类似这样:

 var sData = JSON.stringify({ ids: array}); $.ajax({ url: "/path/to/method", data: sData, method: 'POST', contentType: "application/json; charset=utf-8", success: function (result) { }, error: function (result) { } }); 

在你的情况下,它可能是:

  var dataValues = JSON.Stringify({ ids: array, id: $('#idNumber').val(), orderId: $('#orderId').val() }); $.ajax({ url: "/path/to/method", data: sData, method: 'GET', contentType: "application/json; charset=utf-8", success: function (result) { }, error: function (result) { } }); // $.getJSON("/path/to/method", dataValues, function(){});