无法发布字符串数组到ASP.NET MVC3

问题描述:

我有一个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

您需要使用$.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'头文件。 –