0

我有这个用于插入、更新、删除和显示城市的淘汰视图模型

function City(data) {
    this.CityId = ko.observable(data.CityId);
    this.CityName = ko.observable(data.CityName);
}
function CityViewModel() {
    var self = this;
    self.Citys = ko.observableArray([]);
    self.SelectedCity = ko.observable();
    self.EditingCity = ko.observable(new City({ CityId: '', CityName: '' }));

    self.EditCity = function (city) {
        $.ajax("/Controller/GetSingalCity/" + ko.toJSON(city.CityId), {
            data: ko.toJSON({ CityId: city.CityId }),
            type: "POST", contentType: "application/json",
            success: function (result) {
                if (result.Success) {
                    var cityid = result.Data.CityId;
                    var cityname = result.Data.CityName;
                    self.EditingCity(new City({ CityId: cityid, CityName: cityname }));
                }
                else {
                    alert("Error..");
                }
            }
        }); 
    };
}

每次插入更新删除时,我都必须使用此代码使用

self.EditingCity(new City({ CityId: cityid, CityName: cityname }));

或者

self.EditingCity(new City({ CityId: '', CityName: '' }));

我不想装箱 self.EditingCity(new City({ CityId: '', CityName: '' })); 对于每个操作(插入、更新、删除)。谁能告诉我怎么做?我是淘汰赛的初学者....

4

1 回答 1

1

您不需要创建新的 City 对象。相反,只需更新现有的。任何与该EditingCity对象数据绑定的视图都应自动更新。

所以,而不是写:

self.EditingCity(new City({ CityId: cityid, CityName: cityname }));

你应该写:

self.EditingCity().CityId(newCityId);
self.EditingCity().CityName(newCityName);
于 2013-06-03T11:34:40.317 回答