2010-09-09 55 views
23

我有以下的地方,我要發送列表/陣列控制器的MVC方法:發送列表/數組作爲參數與jQuery的getJSON

var id = []; 
var inStock = []; 

$table.find('tbody>tr').each(function() { 
    id.push($(this).find('.id').text()); 
    inStock.push($(this).find('.stocked').attr('checked')); 
}); 

var params = {}; 
params.ids = id; 
params.stocked = inStock; 

$.getJSON('MyApp/UpdateStockList', params, function() { 
    alert('finished'); 
});  
在我的位指示

public JsonResult UpdateStockList(int[] ids, bool[] stocked) { } 

兩個參數爲null。

需要注意的是,如果我改變PARAMS到單品

params.ids = 1; 
params.stocked = true; 

public JsonResult UpdateStockList(int ids, bool stocked) { } 

那麼它的工作原理確定,所以我不認爲這是一個路由問題。

回答

39

嘗試將traditional標誌:

$.ajax({ 
    url: '/home/UpdateStockList', 
    data: { ids: [1, 2, 3], stocked: [true, false] }, 
    traditional: true, 
    success: function(result) { 
     alert(result.status); 
    } 
}); 

工作正常:

public ActionResult UpdateStockList(int[] ids, bool[] stocked) 
{ 
    return Json(new { status = "OK" }, JsonRequestBehavior.AllowGet); 
} 
+0

天才,謝謝!看來在1.4.2的getJson中有一個bug,請參閱http://forum.jquery.com/topic/getjson-breaks-with-1-4-2-when-parameter-argument-is-an-array – fearofawhackplanet 2010-09-09 13:50:06

+2

這不是一個錯誤。這是從以前的版本突破性的變化。這就是爲什麼他們引入了「傳統」參數。 – 2010-09-09 13:52:07

+0

我愛你,男人 – heisenberg 2013-10-09 18:23:23

6

不幸的是,雖然它似乎jQuery提供了一個 「傳統」 的標誌來切換jQuery.ajax這種行爲,它不在jQuery.getJSON上。解決這個問題的一種方法是將全局標記爲:

jQuery.ajaxSettings.traditional = true;

見jQuery.param的文檔:http://api.jquery.com/jQuery.param/ 另請參見發行說明這種變化:http://jquery14.com/day-01/jquery-14(搜索「傳統」)

18

除了要求.ajax(),而不是作爲.getJSON()達林的建議,或設置全局jQuery.ajaxSettings.traditionaltrue爲jrduncans建議,你也可以通過你的params對象上調用the jQuery .param() function結果:

var id = []; 
var inStock = []; 

$table.find('tbody>tr').each(function() { 
    id.push($(this).find('.id').text()); 
    inStock.push($(this).find('.stocked').attr('checked')); 
}); 

var params = {}; 
params.ids = id; 
params.stocked = inStock; 

$.getJSON('MyApp/UpdateStockList', $.param(params, true), function() { 
    alert('finished'); 
});  
+2

這應該是被接受的答案。 – 2016-07-26 20:18:14

+1

是的,我同意。雖然Darin指出傳統的國旗(你真棒不要誤解我的意思),但這個答案讓我們使用getJson,這是OP想要的。 – 2016-09-14 06:13:39

0

在視圖中,生成multiple named fields(不id,如id應該是每場唯一的),指出使用Name not name

var myArrayValues = $('input[name="someString[]"]').map(function() { return $(this).val(); }).get(); 

您可以直接使用此:

@foreach (var item in Model.SomeDictionary) 
{ 
    @Html.TextBoxFor(modelItem => item.Value.SomeString, new { Name = "someString[]" }) 
} 

然後使用jQuery,so檢索輸入字段值在jQuery/AJAX中如下:

$.ajax({ 
    type: "POST", 
    url: "/MyController/MyAction", 
    dataType: 'json', 
    data: { 
     someStrings: $('input[name="someString[]"]').map(function() { return $(this).val(); }).get(), 
     someDates: $('input[name="someDate[]"]').map(function() { return $(this).val(); }).get(), 

然後在MVC的控制器動作中:

[HttpPost] 
public JsonResult MyAction(string[] someStrings, DateTime[] someDates...