我正在传递以下C#AjaxViewModel模型:
namespace Db.ViewModels
{
public class DbAjaxViewModel
{
public DbAjaxViewModel() {
Products = new List<DbProductViewModel>();
}
public List<DbProductViewModel> Products { get; set; }
}
public class DbProductViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public string CategoryId { get; set; }
}
}
..使用以下代码:
[HttpGet]
public ActionResult GetProductsAjax() {
var viewModel = _service.GetAllProductsAjaxViewModel();
return new JsonResult { Data = viewModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
然后我做ko映射:
function callBack(result) {
sprAdmin.product.viewModel = ko.mapping.fromJS(result);
ko.applyBindings(sprAdmin.product.viewModel, $("adminProductWrap")[0]);
}
$.ajax({
type: "GET",
url: url,
success: callBack
});
它很有效。我有这个函数来添加一个空项目到我的viewModel:
addProduct: function () {
function product() {
this.Id = ko.observable("-1");
this.CategoryId = ko.observable("0");
this.Name = ko.observable("");
this.Description = ko.observable("");
this.Price = ko.observable("0");
}
debug.debug("adding new product");
sprAdmin.product.viewModel.Products.push(new product());
var debugArray = sprAdmin.product.viewModel.Products(),
debugData = debugArray[debugArray.length - 1];
debug.debug("id: " + debugData.Id() + ", name: " + debugData.Name() + ", description: " + debugData.Description() + ", price: " + debugData.Price() + ", categoryId: " + debugData.CategoryId());
}
正如您所看到的,debug.debug检索Products()数组的最后一项并显示其内容,这也很有效。
但是
当我将多个项添加到空数组时,执行此操作 var data = ko.mapping.toJSON(viewModel); debug.debug(“ajax submit data:”+ data);
它显示未映射的viewModel转换为JSON的内容,如下所示:
{"Products":[{"Id":"1","CategoryId":"0","Name":"name","Description":"desc","Price":"0"},{}]}
Products数组的第二个(以及进一步存在的)项目绝对是空的。它始终只适用于第一项。
请帮忙。
===
解决方案:
首先,必须声明一个observableArray:
viewModel: {
Products: ko.observableArray([])
}
然后像这样映射:
sprAdmin.product.viewModel.Products(ko.mapping.fromJS(result.Products)());