您必须将 JSON 数组的提交包装在“items”之类的变量中,变量名称匹配很重要。ASP.NET 会自动将 JSON 反序列化为您的对象,无需手动执行。我已经对此进行了全面测试并经常这样做,所以我知道它有效。
[HttpPost]
// Note how the argument name is "items"
public ActionResult MyItems(List<Item> items)
{
// set a breakpoint and check the items List
return Content("success")
}
public class Item
{
// Make sure to use public properties get/set
public string Category {get;set;}
}
还有你的 javascript
function Item()
{
this.Category = ko.observable();
}
function ViewModel()
{
this.Items = ko.observableArray();
this.submit = function() {
// note how we make sure argument name matches "items" as in Controller
var myData = ko.toJSON( { items: this.Items() });
$.ajax({
url: '/Home/MyItems',
contentType: 'application/json',
type: 'POST',
data: myData,
success: function(data){
// check result
}
})
}
}
var vm = new ViewModel();
ko.applyBindings(vm);
var item1 = new Item();
item1.Category("Cat1");
vm.Items.push(item1);
vm.submit();