1

一個簡單的主細節的場景: 服務器如何用json和knockoutjs創建主詳細級聯下拉菜單?

int id 
string Name 
List<Driver> Drivers 

其中驅動器還具有ID和名稱的列表。 作爲JSON從服務器上的MVC Action返回。

現在我有一個knockoutjs模型

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.applyBindings(ViewModel); 

和一些綁定

<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'"> 

問題是:服務器下拉被填充,而司機沒有。 我肯定錯過了一些東西。也許我需要使用映射插件?

回答

0

SelectedServers()返回server.Id而不是server對象。

嘗試刪除optionsValue: 'Id'在SERVERID選擇:

<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

是的,我已經做到了,它幫助..不是很明顯.. –