我目前有 2 个合并的视图模型。现在我想将此 MasterViewModel 数据绑定到页面中的元素,但不确定如何。
这是我的 HTML:
<select data-bind="options: MasterViewModel.VMPR.ProjectName">
</select>
<select data-bind="options: MasterViewModel.VMTT.TaskTypeDetail">
</select>
我的 ViewModels 和绑定模型:
var ProjectDS = function (data) {
var self = this;
self.ProjectID = ko.observable(data.ProjectID);
self.ProjectName = ko.observable(data.ProjectName);
}
var ProjectModel = function (Projects) {
var self = this;
self.Projects = ko.observableArray(Projects);
$.ajax({
url: "CreateTask.aspx/GetTaskProjects",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedProjects =
$.map(Result.d,
function (item) { return new ProjectDS(item); });
self.Projects(MappedProjects);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
var TaskTypeDS = function (data) {
var self = this;
self.TaskTypeID = ko.observable(data.TaskTypeID);
self.TaskTypeDetail = ko.observable(data.TaskTypeDetail);
}
var TaskTypeModel = function (TaskTypes) {
var self = this;
self.Projects = ko.observableArray(TaskTypes);
$.ajax({
url: "CreateTask.aspx/GetTaskTypes",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedTaskType =
$.map(Result.d,
function (item) { return new TaskTypeDS(item); });
self.Projects(MappedTaskType);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
var MasterViewModel = {
VMPR: new ProjectModel(),
VMTT: new TaskTypeModel()
}
$(document).ready(function () {
ko.applyBindings(MasterViewModel);
})
最后,这是我得到的 JSON:
{
"VMPR": {
"Projects": [
{
"ProjectID": 1,
"ProjectName": "Dummy Project"
},
{
"ProjectID": 3,
"ProjectName": "Dummy Project2"
}
]
},
"VMTT": {
"Projects": [
{
"TaskTypeID": 1,
"TaskTypeDetail": "Documentation"
},
{
"TaskTypeID": 2,
"TaskTypeDetail": "Development"
},
{
"TaskTypeID": 3,
"TaskTypeDetail": "Planning"
},
{
"TaskTypeID": 4,
"TaskTypeDetail": "Integration"
},
{
"TaskTypeID": 5,
"TaskTypeDetail": "Deployment"
},
{
"TaskTypeID": 6,
"TaskTypeDetail": "Testing"
}
]
}
}