我通过jquery ajax post将json数据发送到我的控制器动作。我的行动中的IEnumerable总是为空。
我的json是错的还是模型绑定器为什么不将json转换为IEnumerable?
public ActionResult Update(IEnumerable<Teststep> teststeps)
{
//
}
$.ajax({
url: '@Url.Action("Update", "Teststep")',
type: 'POST',
data: [{ "errortext": "oh something bad happended.", "unitid": "10" }, { "errortext": "you got it man.", "unitid": "20"}],
success: function (response) {
debugger;
if (response.success) {
dlg.dialog("close");
// Update UI
}
else {
// Reload the dialog with the form to show model/validation errors
dlg.html(response);
}
}
});
public class Teststep
{
[HiddenInput(DisplayValue = false)]
public int UnitId { get; set; }
public string ErrorText { get; set; }
// some other props removed for readability
}
答案 0 :(得分:1)
为了让集合(数组,ienumebles等)通过模型绑定器正确传递给action方法,我总是必须在ajax调用上设置传统:true选项:
$.ajax({
url: '@Url.Action("Update", "Teststep")',
type: 'POST',
traditional: true,
...
答案 1 :(得分:1)
现在它有效!我在IEnumerable中得到1个项目。问题是弄乱了json; - )
var data = { teststeps: [{ ErrorText: 'bla', UnitId: 10}] };
$.ajax({
url: '@Url.Action("Update", "Teststep")',
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json'
});
[HttpPost]
public ActionResult Update(IEnumerable<Teststep> teststeps)
{
}