我正在将knockout与asp.net mvc结合使用,其中我在asp.net mvc中拥有一个视图模型。我有一个基于服务器端生成的数组列表,该列表基于asp.net mvc视图模型中每个类的属性名的值。例如:Array[] propertyName = { name1, name2, name3 }。现在我需要将所有这些属性名设置为可观察对象,如下所示。我可以在JavaScript中逐个输入它,但问题是它应该根据在asp.net mvc定义的视图模型中可用的属性进行动态设置。现在我正在硬编码name1、name2和name3,但我不知道如何根据从服务器返回的数组使其动态化。
<script>
function TestViewModel() {
var self = this;
self.name1 = ko.observable('@name1') //from view model (need to be dynamic)
self.name2 = ko.observable('@name2') //from view model (need to be dynamic)
self.name3 = ko.observable('@name3') //from view model (need to be dynamic)
self.btn1 = ko.observable(false); //hardcoded base on html
self.btn2 = ko.observable(true); //hardcoded base on html
}
ko.applyBindings(new TestViewModel());
</script>
// What i expect
<script>
function TestViewModel() {
var self = this;
Array[] propertyName = { name1, name2, name3 } // value retrieve from server
@foreach(var item in propertyName) {
// and knockout js can run this
self.@propertyName = ko.observable(@propertyName)
}
self.btn1 = ko.observable(false); //hardcoded base on html
self.btn2 = ko.observable(true); //hardcoded base on html
}
ko.applyBindings(new TestViewModel());
</script>
// fail because self.@propertyName
self.@propertyName = ko.observable(@propertyName)
= expected identifer
ko expected;
self.@(PropertyName) = ...
或者self['@PropertyName'] = ...
。 - haim770data-bind
属性,如果你事先无法预料到已知的视图模型结构。 - haim770