1

我是淘汰赛和 asp.net mvc 的新手。我正在尝试通过淘汰赛在数据库中插入更新删除数据。我的淘汰赛模型是

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.CityId = ko.observable();
    self.CityName = ko.observable();
    self.selectedCity = ko.observable();
    // self.City = ko.observable();

    selectCity = function (item) {
        self.selectedCity(item);
    }
    //load
    loadCitys = function () {
        $.getJSON("/Admin/GetCitys", {}, function (result) {
            var mappedCitys = ko.utils.arrayMap(result.Data, function (item) {
                return new City(item);
            });
            self.Citys([]);
            self.Citys.push.apply(self.Citys, mappedCitys);
        });
    }
    //edit
    EditCity = function (item) {
        //what need to do here 
        // is it possible to fill the hidden fild and the text box ??
    }
    //save
    SaveCity = function (item) {
        City = new City(item);
        $.ajax({
            type: "POST",
            url: "/Admin/SaveCity",
            data: ko.toJSON({ City: City }),
            contentType: "application/json",
            success: function (result) {
                if (result.Edit) {
                    City.CityId = result.Success;
                    City.CityName = item.CityName;
                    self.Citys.push(City);
                    toastr.success('City Information Save Successfully', 'Success');
                }
                else if (result.Edit == false) {
                    toastr.success('City Information Update Successfully', 'Success');
                }
                else {
                    toastr.error('There is an error please try again later', 'Errror');
                }
            }
        });
    }
    //delete
    DeleteCity = function (City) {
        $.ajax("/Admin/DeleteCity", {
            data: ko.toJSON({ CityId: City.CityId }),
            type: "POST", contentType: "application/json",
            success: function (result) {
                if (result.Success) {
                    self.Citys.remove(City);
                    toastr.success('City Remove Successfully', 'Success');
                }
                else {
                    alert("Error..");
                }
            }
        });
    } 
}
 (function () {
    ko.applyBindings(new CityViewModel, document.getElementById("Citys"));
    loadCitys();
});

我的 HTML 代码是

<table class="table table-striped">
          <thead>
            <tr>
              <th>City Id</th>
              <th>City Name</th>
              <th></th>
              <th></th>
            </tr>
          </thead>

          <tbody data-bind="foreach: $root.Citys">
            <tr data-bind="click: selectCity">
              <td><span data-bind="text:CityId"></span></td>
              <td><span data-bind="text:CityName"></span></td>
              <td><button data-bind="click: EditCity" class="btn btn-primary">Edit</button></td>
              <td><button data-bind="click: DeleteCity" class="btn btn-danger">Delete</button></td>
            </tr>
          </tbody>
        </table>

<fieldset>
              <legend>Add new / Edit City</legend>
              <label>City name</label>
              <input type="hidden" data-bind="value: CityId" />
              <input type="text" data-bind="value: CityName" placeholder="Type city name…">
              <button type="submit" data-bind="click: SaveCity" class="btn">Submit</button>
          </fieldset>

使用此代码,我可以将数据表单数据库成功显示在我的视图文件中,我从数据库中删除数据,我也可以将数据插入数据库,但这是一个问题,当我更改文本框值时,我只能第一次保存数据(没有页面刷新)并尝试保存城市信息然后它说(在我的javascript代码上的Firebug中):

TypeError: City 不是构造函数 City = new City(item);

我的问题是我在这段代码中做错了什么,我试图在点击编辑按钮时填充文本框和隐藏字段,我该怎么做?提前致谢。

4

1 回答 1

2

There are a number of faults with your javascript, including:

  • The methods on your viewmodel, such as SaveCity, DeleteCity, EditCity are all being defined without the 'this/self' prefixes, therefore they are being added to the global namespace.
  • In your SaveCity method, your are assigning a new instance of the City class to a variable called 'City', therefore destroying the City class. It will work the first time, but any other attempts to create an instance of a City will yield an exception.

Anyway, this should be a working version of your script and HTML without the ajax stuff. You will need to adapt that yourself. I have also created a working JsFiddle here..

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: null, CityName: ''}));  

    self.EditCity = function(city){
        self.EditingCity(new City(ko.toJSON(city)));  
    };

    //load
    self.loadCitys = function () {
        self.Citys().push(new City({CityId: '1245', CityName: 'Los Angeles'}));
        self.Citys().push(new City({CityId: '45678', CityName: 'San Diego'}));
    };

    //save
    self.SaveCity = function () {
        var city = self.EditingCity();

        if(city.CityId()){        
            var cityIndex;

            for(var i = 0; i < self.Citys().length; i++) {
                if(self.Citys()[i].CityId() === city.CityId()) {
                    cityIndex = i;
                    break;
                }
            }

            self.Citys[cityIndex] = city;
        }
        else{
            city.CityId(Math.floor((Math.random()*1000000)+1));
            self.Citys.push(city);
        }

        self.EditingCity(new City({CityId: null, CityName: ''}));
    }
    //delete
    self.DeleteCity = function (city) {        
        self.Citys.remove(city);
    }; 
}


var viewModel = new CityViewModel();
viewModel.loadCitys();
ko.applyBindings(viewModel, document.getElementById("Citys"));

HTML

    <table class="table table-striped">
  <thead>
    <tr>
      <th>City Id</th>
      <th>City Name</th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody data-bind="foreach: Citys">
    <tr data-bind="click: $root.SelectedCity">
      <td><span data-bind="text:CityId"></span></td>
      <td><span data-bind="text:CityName"></span></td>
      <td><button data-bind="click: $root.EditCity" class="btn btn-primary">Edit</button></td>
      <td><button data-bind="click: $root.DeleteCity" class="btn btn-danger">Delete</button></td>
    </tr>
  </tbody>
</table>

<fieldset data-bind='with:EditingCity'>
    <legend>Add new / Edit City</legend>
    <label>City name</label>
    <input type="hidden" data-bind="value: CityId" />
    <input type="text" data-bind="value: CityName" placeholder="Type city name" />
    <button type="submit" data-bind="click: $root.SaveCity" class="btn">Submit</button>
</fieldset>
于 2013-05-30T21:14:39.407 回答