2017-04-04 19 views
0

我有一個MVC3控制器動作:無法發佈字符串數組到ASP.NET MVC3

public ActionResult DoStuff(DoStuffModel model) 

DoStuffModel看起來是這樣的:

public class DoStuffModel 
{ 
    public long SomeId { get; set; } 
    public List<string> Codes { get; set; } 
} 

在我的jQuery我這個:

var postData = { 
    SomeId: 1, 
    Codes: ["code1", "code2", "code3"] 
}; 

$.post(url, postData, function (data) {}); 

該URL是正確的。該postData這個樣子的,當我登錄它:

enter image description here

SomeId得到正確綁定,但Codes保持爲空。到底是怎麼回事?

+0

你的模型預計的數組稱爲代碼,但在你的開發工具這表明,在JavaScript對象數組名是PiCodes。你能檢查是否有幫助嗎? – MarioMucalo

+0

只是一個猜測,但你有沒有嘗試過'public string [] Codes {get;組; }' –

+0

對我而言不好的截圖,對不起。名稱相應。 – ohyeah

回答

1

您需要使用$.ajax()方法並設置正確的ajax選項並將數據串聯起來。

$.post()方法在發送數據作爲application/x-www-form-urlencoded; charset=UTF-8,這意味着你將需要產生用在索引的集合,以使DefaultModelBinder綁定它 - 使用含有您的當前對象例如

var postData = { SomeId: 1, 'Codes[0]': 'code1', 'Codes[1]': 'code2', 'Codes[2]': 'code3'}; 

的代碼數組將

$.ajax({ 
    url: url, 
    type: 'post', 
    contentType: 'application/json', 
    data: JSON.stringify({ model: postData }) 
    success: function(data) { 
     .... 
    } 
}); 
+0

感謝您的幫助!但是,'[0] .Codes'似乎不是正確的語法。我的智能感知似乎至少抱怨它。 – ohyeah

+0

對不起,忘了引號(注意你也可以在這種情況下使用''Codes [0]''(簡單對象的集合) –

+0

由於你發送的是JSON,你不需要使用'Codes [0]'。 OP的原始'postData'是正確的,他只是錯過了'application/json'頭文件。 –