保存Knockout js下拉值

时间:2014-04-24 14:34:38

标签: javascript knockout.js

您好我想将下拉列表的选定值保存到服务器,但每次返回相同的值而不是我选择的更新值。

我的知道:

      var stateModel = {
          CountriesList: ko.observableArray([]),
          StateId: ko.observable(),
          StateName: ko.observable('').extend({ required: true }),
          ShortName: ko.observable('').extend({ required: true }),
          IsActive: ko.observable(true),
          CountryId: ko.observable()



      var stateViewModel = function () {
          var self = this;
          self.StateModel = stateModel;
          self.CountriesList = ko.observableArray([]);
          self.StatesList = ko.observableArray([]);
          self.CountryId = ko.observable();

我在按钮点击中调用此添加状态,但每次它在args中退回时如下:
{" argBO" {" CountriesList":[]," Statename的":" ASDF"" SHORTNAME&# 34;:" S"" IsActive":真}}

      self.AddState = function () {
              var args = JSON.stringify({ argBO: jQuery.parseJSON(ko.toJSON(self.StateModel)) });
              alert(args);
              ajax.Post("AddState.aspx/AddState", args, false).success(function (data) {

      };

  var vm = new stateViewModel();

          ajax.Get("AddCountry.aspx/getCountries", { IsActive: true }, false).success(function (data) {
              vm.CountriesList(data.d);
          });

          ko.applyBindings(vm, document.getElementById("divcountry"));


          ko.applyBindings(stateViewModel, document.getElementById("state_container"));

          var vm1 = new stateViewModel();
          ajax.Get("AddState.aspx/getStates", { IsActive: true }, false).success(function (data) {
              vm1.StatesList(data.d);
          });

Dropdown在divcountry中,StateName,ShortName在state_containerdiv中。实际上我在DropDown旁边的divCountry中有一个虚拟标签,它根据Dropdown选择给我正确的选择值...

        <div id="divcountry">          
             <select   data-bind="options: CountriesList,optionsText: 'CountryName',optionsValue:'CountryId',value:CountryId,optionsCaption: 'Select Country..'" style="width: 148px">
            </select>
            <label data-bind="text: CountryId"></label>
         </div>

我哪里错了?我从2天开始在线搜索!!我会很感激!!

2 个答案:

答案 0 :(得分:1)

我认为如果我们将stateModel修改为可能适合您的类,

  var stateModel = function(){
          CountriesList: [],
          StateId: '',
          StateName: '',
          ShortName: '',
          IsActive: true,
          CountryId: 0
}


      var stateViewModel = function () {
          var self = this;
          self.StateModel = new ko.observable(new stateModel());
          self.CountriesList = ko.observableArray([]);
          self.StatesList = ko.observableArray([]);
          self.CountryId = ko.observable();
          }

并将self.StateModel更改为self.StateModel()

答案 1 :(得分:0)

我再次敦促花费适当的时间阅读knockoutjs文档并充分理解绑定上下文等。因为即使你声明你理解了绑定上下文,过去几天你所有的问题都表明不是这样。之后再问问自己为什么要首先发布vm.StateModel。

vm.CountryId不等于vm.StateModel.CountryId