无法发布字符串数组到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
这个样子的,当我登录它:
的SomeId
得到正确绑定,但Codes
保持为空。到底是怎么回事?
您需要使用$.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] .Codes'似乎不是正确的语法。我的智能感知似乎至少抱怨它。 – ohyeah
对不起,忘了引号(注意你也可以在这种情况下使用''Codes [0]''(简单对象的集合) –
由于你发送的是JSON,你不需要使用'Codes [0]'。 OP的原始'postData'是正确的,他只是错过了'application/json'头文件。 –
你的模型预计的数组称为代码,但在你的开发工具这表明,在JavaScript对象数组名是PiCodes。你能检查是否有帮助吗? – MarioMucalo
只是一个猜测,但你有没有尝试过'public string [] Codes {get;组; }' –
对我而言不好的截图,对不起。名称相应。 – ohyeah