0

我有 2 个填充有 knockout.js 的下拉列表,我有 2 个问题:

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

4

1 回答 1

1

1.try populating ko model with data from MVC model like so:

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

2.You need to pass the model (even though invalid) with SelectedStreet & SelectedHouse populated back to the View.

于 2013-02-21T10:14:41.347 回答