我在后端有这个功能:
public JsonResult GetEstados()
{
List<State> states = new List<State>() {
new State(1, "Acre", "AC"),
new State(2, "Alagoas", "AL"),
new State(3, "Amapá", "AP")
...
};
List<City> cities = new List<City>() {
new City(1, "Rio Branco", states[0]),
new City(2, "Brasília", states[6]),
new City(4, "Belo Horizonte", states[12])
....
};
return Json(new {
states = states,
cities = cities
}, JsonRequestBehavior.AllowGet);
}
目的是获取城市和州的集合。当我更改所选状态时,我想select
用属于该状态的城市填充元素。然后,我在下面创建了 KnockoutJS 代码:
function State(state) {
this.id = state.Id;
this.name = state.Name;
this.abbreviation = state.Abbreviation;
}
function Cidade(city) {
this.id = city.Id;
this.name = city.Name;
this.state = new State(ko.toJS(city.State));
}
function IndexViewModel() {
var self = this;
self.states = ko.observableArray();
self.cities = ko.observableArray();
self.selectedState = ko.observable();
self.selectedCity = ko.observable();
self.citiesFromSelectedState = ko.computed(function() {
return ko.utils.arrayFilter(self.cities(), function(city) {
return city.state().id() == self.selectedState();
}
}, self);
}
var model = new IndexViewModel();
$.ajax({
type: 'GET',
async: false,
url: '/Home/GetEstados/',
success: function(result) {
ko.utils.arrayForEach(result.states, function(state) {
model.states().push(new State(ko.toJS(state)));
});
ko.utils.arrayForEach(result.cities, function(city) {
model.cities().push(new City(ko.toJS(city));
});
}
});
ko.applyBindings(model);
好的,这是创建城市和州的 observableArray 的过程。
在我看来,我有以下代码来显示州和城市:
<div class="form-group col-lg-4 col-md-4 col-sm-6 col-xs-12">
<label class="sr-only" for="estado">State</label>
<select class="form-control" data-bind="
options: states,
optionsText: 'name',
optionsValue: 'id',
value: selectedState,
optionsCaption: ' '"></select>
</div>
<div class="form-group col-lg-8 col-md-8 col-sm-6 col-xs-12">
<label class="sr-only" for="cidade">City</label>
<select class="form-control" data-bind="
options: citiesFromSelectedState,
optionsText: 'name',
optionsValue: 'id',
value: selectedCity,
optionsCaption: ' '"></select>
</div>
但它不能正常工作。我做错什么了吗?谢谢大家的帮助!