【发布时间】:2014-03-21 07:09:58
【问题描述】:
我正在尝试使用 knockout.js 创建一个网格,方法如下 http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/
当我尝试将值从 viwe 发布到控制器时,我总是得到一个 count=0 值。但是当我尝试使用警报检查数据是否具有视图模型时。它按预期出现。有没有人面临/修复了这个问题。请突出显示错误所在。
她是我的模特。
public class GiftModel
{
public string Title { get; set; }
public string Price { get; set; }
}
控制器中的代码:
public ActionResult Index()
{
var initialState = new[] {
new GiftModel { Title = "Head First C#", Price = "49.95" },
new GiftModel { Title = "Head First Js", Price = "78.25" }
};
return View(initialState);
}
[HttpPost]
public ActionResult Index(IEnumerable<GiftModel> gifts)
{
return View();
}
这是我在做的事情。
var initialData = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = {
gifts : ko.observableArray(initialData),
addGift: function () {
this.gifts.push({ Title: "", Price: "" });
},
removeGift: function (gift) {
this.gifts.remove(gift);
},
save: function() {
var data = ko.toJSON(this.gifts);
alert(data);
ko.utils.postJson(location.href, { gifts: data });
}
};
ko.applyBindings(viewModel,document.body);
我也尝试过使用普通的 Ajax 帖子。但我仍然得到同样的结果。
编辑:这是我收到的警报
[{"Title":"Head First C#","Price":"49.95"},{"Title":"Head First Js","Price":"78.25"}]
更新:如果我直接通过弹出内容控制器可以识别数据。
var model = [{"Title":"Head First C#","Price":"49.95"},{"Title":"Head First Js","Price":"78.25"}];"Status": "Reserved" }];
$.ajax({
url: '/Grid/Index',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
success: function (result) {
}
});
【问题讨论】:
-
无需致电
ko.toJSON()。在内部,ko.utils.postJson()为您完成。 -
是的,我已经开始这样做了,但没有给我输出然后我已经转移到 Ajax Calls。谢谢@haim770
-
试试
ko.utils.postJson(location.href, this.gifts);。
标签: jquery asp.net-mvc-4 knockout.js knockout-mvc