2013-02-21 130 views
0

我有填充knockout.js 2名下拉列表,我有2個問題:ASP.NET MVC 4 KNOCKOUT.JS

1)爲什麼這個人是從Model.StreetList

@Html.DropDownListFor(m => m.SelectedStreet, Model.StreetList, new {onchange = "FetchHouses();"}) 
填充

但這並不

@Html.DropDownListFor(m => m.SelectedStreet, Model.StreetList, new {onchange = "FetchHouses();", @data_bind = "options: StreetList, optionsText: 'Name', optionsValue: 'Id', optionsCaption: 'Select...'"}) 

那麼,這可以通過從型號默認填充它,但如果某些事件發生與基因敲除結合填充它?

2)表單提交後,如果ModelState無效,那些2個列表中的選定值將丟失。我該如何解決這個問題?

<p> 
    @Html.LabelFor(m => m.SelectedStreet, @Resources.RegistrationStreet) 
    @Html.DropDownListFor(m => m.SelectedStreet, Model.StreetList, new {onchange = "FetchHouses();", @data_bind = "options: StreetList, optionsText: 'Name', optionsValue: 'Id', optionsCaption: 'Select...'"}) 
</p> 
<p> 
    @Html.LabelFor(m => m.SelectedHouse, @Resources.RegistrationHouse) 
    @Html.DropDownListFor(m => m.SelectedHouse, Model.HouseList, new { @data_bind="options: HouseList, optionsText: 'Number', optionsValue: 'Id'"}) 
</p> 

任何幫助表示讚賞!

編輯:

knockout.js上改變事件發生的結合,它工作正常,問題是,雖然改變事件不解僱我想從MVC模型 填充下拉菜單下面是JS代碼做結合:

function CascadingDdLViewModelStreet() { 
    this.StreetList = ko.observableArray([]); 
    this.HouseList = ko.observableArray([]); 
} 

var objVMStreet = new CascadingDdLViewModelStreet(); 
ko.applyBindings(objVMStreet); 

function FetchStreets() { 
    objVMStreet.HouseList([]); 
    objVMStreet.StreetList([]); 
    var cityCode = $("#SelectedCity").val(); 
    $.getJSON("/Account/GetStreets/" + cityCode, null, function(data) { 
     objVMStreet.StreetList(data); 
    }); 

} 

function FetchHouses() { 
    var streetCode = $("#SelectedStreet").val(); 
    $.getJSON("/Account/GetHouses/" + streetCode, null, function(data) { 
     objVMStreet.HouseList(data); 
    }); 
} 

這裏是一個全碼:

查看:http://pastebin.com/jva9ff8A

莫德爾:http://pastebin.com/vDQkg0d5

控制器:http://pastebin.com/avBuRy9D

+0

看起來你正在做級聯下拉,這正是我目前的工作。我使用這個例子:http://marcofranssen.azurewebsites.net/knockout-that-c​​ascading-dropdown/和http://knockoutmvc.com非常有用! – Tsar 2013-02-21 10:59:53

回答

1

1.try填充KO模型與MVC模型數據,像這樣:

function CascadingDdLViewModelStreet() { 
    this.StreetList = ko.observableArray(@Html.Raw(Json.Encode(Model.StreetList))); 
    this.HouseList = ko.observableArray([]); 
} 

2.You需要傳遞模型(即使無效)與SelectedStreet & SelectedHouse填充回視圖。

+0

1)請參閱問題2)中的編輯我做了,在問題中添加了完整的代碼。謝謝 – 2013-02-21 10:42:54

+0

對不起,pastebin被阻止了。請參閱q1上的編輯 – Tsar 2013-02-21 10:57:23

+0

如果Model.StreetList是ICollection,它會起作用,謝謝 – 2013-02-22 09:08:34