我正在尝试学习如何使用淘汰赛,并且尚未找到我想要实现的简单示例。我只是想将我的mvc Model类中的List绑定到我的viewModel for knockout。例如,如果我有下面的模型..这是一个类文件。
public class PropaneMaintModel
{
public List<PropaneMaintAssignment> PropaneMaint{get;set;}
public List<string> LocationIds { get; set; }
public int? SelectedLocation { get; set; }
}
public class PropaneMaintAssignment
{
public int StoreNumber { get; set; }
public int Tanks { get; set; }
[Required(ErrorMessage="Tank Size must have a value")]
[Range(0,10000,ErrorMessage="Tank Size must be between 0 and 10000.")]
public int TankSize { get; set; }
}
我如何获得列表&#34; PropaneMaint&#34;使用淘汰赛绑定?我需要在列表中添加/删除类似于淘汰站点上的示例。我的viewmodel定义如下,但它不起作用。
function propaneMaintViewModel() {
var viewModel = this;
viewModel.PropaneMaint = ko.observableArray([]);
viewModel.addNew = function () {
viewModel.PropaneMaint.push(
{
StoreNumber: 0,
Tanks: 0,
TankSize: 0
}
);
}
}
ko.applyBindings(new propaneMaintViewModel());
答案 0 :(得分:0)
Knockout没有直接绑定到任何c#模型。您可以做的是将MVC视图模型序列化为json对象,然后绑定它。 IE:
function bindModels(arr) {
var propaneMaintAssignments = new Array();
for (var i = 0; i < arr.length; i++)
propaneMaintAssignments.push(new PropaneMaintAssignment(arr[i]));
return propaneMaintAssignments;
}
function PropaneMaintAssignment(model) {
for(var property in model)
this[property] = model[property]; //bind all properties
}
var json = @Html.Raw(new JavaScriptSerializer().Serialize(Model.PropaneMaint)); //results in an array
var list = bindModel(json); //makes an array of named objects
viewModel.PropaneMaint(list); //adds that array of named objects to your observableArray