我正在尝试使用ko.mapping插件来更新我的viewModel。首次打开局部视图时,我使用以下内容:
$(document).ready(function () {
var data = function () {
return @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
}();
model = ko.viewmodel.fromModel(ResultModel(data));
ko.applyBindings(new model);
});
数据似乎已绑定并在我的视图中正确显示。我的viewModel如下:
function Member(data) {
var self = this;
self.FirstName = ko.observable(data.FirstName);
self.LastName = ko.observable(data.LastName);
self.CountyCollections = ko.observableArray(data.CountyCollections);
self.CountiesPurchased = ko.observableArray(data.CountiesPurchased);
}
var ResultModel = function (data) {
var self = this;
self.Member = new Member(data);
self.addCounty = function () {
var county = {
countyCode: ko.observable(""),
countyName: ko.observable(""),
};
self.Member.CountyCollections.push(county);
}.bind(self);
self.removeCounty = function (county) {
self.Member.CountyCollections.remove(county);
}.bind(self);
};
问题是当我尝试使用ko.mapping.fromJS从控制器更新viewModel时。
$("#SaveReferralsClick").click(function (e) {
$.ajax({
url: "/mySurface/Save_Counties",
type: "POST",
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
cache: false,
async: false,
data: ko.toJSON(Member),
success: function (result) {
ko.mapping.fromJS(result, {}, ResultModel.Member);
}
});
});
当我检查结果(success: function (result) {
)中返回的数据时,它似乎是正确的并且已更新。但是当我运行ko.mapping.fromJS(result, {}, ResultModel.Member)
时,viewModel不会更新。
我尝试过调用ko.mapping.fromJS(result, {}, ResultModel.Member)
的多种变体。例如,当我尝试
ko.mapping.fromJS(result, {}, ResultModel.Member(result))
我收到错误消息,说成员不是构造函数。它指的是以下行:
self.Member = new Member(data);
我们非常感谢任何建议。
答案 0 :(得分:0)
在评论中做了一些澄清后,似乎ajax
调用函数中的函数不是视图模型的一部分,从而导致一些上下文问题。在此澄清简化视图模型后应如何:
var ViewModel = function (data) {
var self = this;
self.mappedModel = new Model(data);
// This method was outside of the model, I moved it here.
self.load = function() {
$.ajax({
..., // some ajax parameters
success: function (data) {
// map received data to model
ko.mapping.fromJS(data, {}, self.mappedModel);
}
});
};
};
// Some Model
function Model(data) {
var self = this;
self.Collection = ko.observableArray(data.Collection);
}