淘汰未绑定服务器上的更新数据

本文关键字:更新 数据 服务器 绑定 淘汰 | 更新日期: 2023-09-27 18:21:45

我正在尝试使用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);
    });

数据似乎被绑定了,并且在我的视图中显示正确。我的视图模型如下:

  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))我收到一个错误,说Member不是构造函数。它指的是以下行:

 self.Member = new Member(data);

任何建议都将不胜感激。

淘汰未绑定服务器上的更新数据

在注释中进行了一些澄清后,似乎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);
}

工作演示