Связыватель модели не преобразует json в IEnumerable<T>
Я отправляю данные json своему контроллеру через jjery ajax post. 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
}
2 ответа
Теперь это работает! Я получаю 1 предмет в IEnumerable. Проблема была в испорченном 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)
{
}
Для того, чтобы коллекции (массивы, ienumerables и т. Д.) Правильно проходили через привязку модели к методу действия, мне всегда приходилось устанавливать традиционную опцию: true при вызове ajax:
$.ajax({
url: '@Url.Action("Update", "Teststep")',
type: 'POST',
traditional: true,
...