2011-08-19 106 views
7

我想,並努力,通過JSON發送一個數組到MVC控制器的行動。通過JSON發送數組到MVC控制器?

這裏是我有什麼,什麼我已經試過......

//Get checked records 
var $checkedRecords = $(':checked'); //e.g. 3 rows selected = [input 4, input 5, input 6] 

//Have tried following: 
sendingVar: $checkedRecords.serializeArray(); // gives array of 0's 
sendingVar: JSON.stringify($checkedRecords); // gives "{\"length\":1,\"prevObject\":{\"0\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"length\":1},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"selector\":\":checked\",\"0\":{}}"...wtf 

//Post 
$.post(url, { sendingVar: sendingVar }, function(data) {alert(data); }); 

我該怎麼辦呢?

編輯:對那些建議發送$checkedRecords「原樣」從頂線 - 這是行不通的。我什麼地方得到一個奇怪的例外jQuery框架:(

uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://.../.../.../jquery-1.4.4.min.js :: <TOP_LEVEL> :: line 141" data: no] 

,我認爲意味着它正試圖分配空的東西它不能

編輯:我使用MVC2不是3

EDIT2:@後周一的答案 - 的問題是由於我怎麼都內置了陣列狀[input 4, input 5, input 6]而不是[4,5,6] - 任何想法我怎麼能剛剛得到的陣列,而不是在值

編輯3:停止投票重複,當它不是。您是否真的閱讀過我的問題或閱讀過相關的問題?這是一個不同的問題

@Daveo:

I don't want to build in an overriding custom attribute just to send an array from JSON, that is rediculous正如我們已經覆蓋了這個問題,這是沒有必要的。

MVC3 - irrelevant

+1

可能重複的:http://stackoverflow.com/questions/320291/how-to-post-an-array-複雜的對象與json-jQuery的 - 到asp網絡mvc控制和http://stackoverflow.com/questions/4789481/post-an-array-of-objects-via-json-to- asp-net-mvc3 – Daveo

+0

你想要的結果是什麼?你的數組是jQuery對象,stringify版本對我來說很合適。你期待它看起來像什麼? – BZink

+0

它只是一個包含檢查項目的字符串ID的數組。我想checkedRecords包含所有選中項目ID的數組。所選輸入的「值」包含我需要的ID值。 – baron

回答

22

這裏是我的演示,使用MVC2,希望有幫助〜

成功的關鍵是traditional

設置traditional參數設置爲true

$(function(){ 
    var a = [1, 2]; 
    $.ajax({ 
     type: "POST", 
     url: "<%= ResolveUrl("~/Home/PostArray/") %>", 
     data: {orderedIds: a}, 
     dataType: "json", 
     traditional: true, 
     success: function(msg){alert(msg)} 
    }); 
}) 

因爲jQuery的1.4此參數存在,因爲將對象序列化爲查詢參數的機制已更改。

和行動是〜

[HttpPost] 
public ActionResult PostArray(int[] orderedIds) 
{ 
    return Content(orderedIds.Length.ToString()); 
} 
+0

不幸的是,這是行不通的。控制器方法中'orderedIds'爲空。我懷疑是因爲ajax實際上做了一個'GET'? – baron

+1

@baron - 在我的位置,它工作正常。 'orderedIds'是一個參數名稱 – Monday

+1

嗯道歉,你是正確的這段代碼確實有效。所以問題在於我如何使用'var $ checkedRecords = $(':checked');''給我'[input 3,input 4,input 5]'我真正需要的地方獲取被檢查Id的數組:'' [1,2]'。謝謝 – baron

0

你也可以用JSON.stringyfy來發送的數據作爲一個字符串,然後使用JavaScriptSerializer class以檢索數據。

在C#代碼,來獲取數據,將是這樣的:

JavaScriptSerializer js = new JavaScriptSerializer(); 

js.Deserialize<T>(string paramiter);