开发者

how can one create a master detail cascading dropdowns with json and knockoutjs?

A simple master details scenario: list of servers

int id
string Name
List<Driver> Drivers

where Driver also has an Id and Name. returned as JSON from MVC Action on server.

Now i have a knockoutjs model

  var ViewModel;
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  ViewModel = {
    IpAddress: ko.observable($("#IpAddress").val()),
    Servers: ko.observableArray([]),
    SelectedServer: ko.observable()
  };
  ViewModel.ValidIp = ko.dependentObservable(function() {
    return /^(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))$/i.exec(this.IpAddress());
  }, ViewModel);
  ViewModel.GetSnmpData = ko.dependentObservable(function() {
    if (this.lastSnmpRequest) {
      this.lastSnmpRequest.abort();
    }
    if (this.ValidIp()) {
      return this.lastSnmpRequest = $.ajax({
        url: GetPrinterDataUrl,
        type: "POST",
        data: {
          IpAddress: this.IpAddress()
        },
        success: __bind(function(data) {
          this.Servers(data.Servers);

        }, this)
      });
    }
  }, ViewModel);
  ko.applyBind开发者_JS百科ings(ViewModel);

and some bindings

<input name="IpAddress" id="IpAddress" type="text" data-bind="value: IpAddress ,valueUpdate: 'afterkeydown'" value=""/>
<select name="ServerId" id="ServerId" data-bind="options: Servers,optionsText:'Name' ,optionsValue:'Id', value: SelectedServer"  />  
<select name="DriverId" id="DriverId" data-bind="options: SelectedServer()? SelectedServer().Drivers: null,optionsText:'Name',optionsValue:'Id'">

problem is: servers dropdown gets populated, while drivers does not. I'm surely missing something. Maybe i need to use mapping plugin?


SelectedServers() returns server.Id instead of server object.

Try remove optionsValue: 'Id' in the ServerId select:

<input name="IpAddress" id="IpAddress" type="text" data-bind="value: IpAddress ,valueUpdate: 'afterkeydown'" value=""/>
<select name="ServerId" id="ServerId" data-bind="options: Servers, optionsText:'Name', value: SelectedServer"></select>
<select name="DriverId" id="DriverId" data-bind="options: SelectedServer()? SelectedServer().Drivers: null,optionsText:'Name',optionsValue:'Id'"></select>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜