我的MVC模型中有对象列表,如下所示。
@Html.EditorFor(model => model.LstEmploymentHistory)
<button id="btnAddHistory" data-bind="click: addHistory">Add one</button>
我需要在加载时将它绑定到Knockout可观察数组。
<script type="text/javascript">
//Data
var History = function () {
var self = this;
self.CompanyName = ko.observable();
self.Designation = ko.observable();
self.StartDate = ko.observable();
self.EndDate = ko.observable()
};
var viewModelEmploymentHistory = function () {
// Operations
var self = this;
self.historyList = ko.observableArray([new History()]); // Put one line in by default
self.addHistory = function () { self.historyList.push(new History()) }
self.removeHistory = function (history) {
self.historyList.remove(history)
}
self.educationList = ko.observableArray([new Education()]); // Put one line in by default
self.addEducation = function () { self.educationList.push(new Education()) };
self.removeEducation = function (education) {
self.educationList.remove(education)
}
};
//Data
var Education = function () {
var self = this;
self.Degree = ko.observable();
self.YearOfPassing = ko.observable();
self.Percentage = ko.observable();
self.Institute = ko.observable()
};
//var masterVM = (function () {
// this.viewModelEducationalDetails = new viewModelEducationalDetails(),
// this.viewModelEmploymentHistory = new viewModelEmploymentHistory();
//})();
//ko.applyBindings(masterVM)
ko.applyBindings(new viewModelEmploymentHistory());
// ko.applyBindings(new viewModelEducationalDetails(), document.getElementById("containerEducation"));
//ko.applyBindings(new viewModelEmploymentHistory(), document.getElementById("containerHistory"));
</script>
任何人都可以帮我解决在页面加载时将C#列表绑定到可观察数组的问题。?
答案 0 :(得分:2)
您需要使用JavaScript理解的格式,例如JSON.。
因此,在您的控制器中,您需要serialise the model into a JSON string
类似的东西:
related_name='profile'
然后你可以在JavaScript / MVC中使用它,有几种方法可以做到这一点。最简单的方法是将其写入输入
Model.JsonString = JsonConvert.SerializeObject(Model.LstEmploymentHistory);
@Html.HiddenFor(h => h.JsonString);
然后turn this back into an array:
var Json = document.getElementById('JsonString').value;
然后你需要将它绑定到你的observable中。你还没有真正解释过这是怎么回事,所以我会把这个留给你......
答案 1 :(得分:0)
如果在Razor中绑定,则可以使用以下内容:
var myModel = {
LstEmploymentHistory: @Html.Raw(Json.Encode(Model.LstEmploymentHistory))
};