我正在使用ajax填充下拉列表。
var getCertifications = function () {
$.getJSON("/Provider/GetCertifications", function (data) {
$.each(data, function (i, item) {
var certification_data = "<option value=" + item.CertificationID + ">" + item.Certification + "</option>";
$(certification_data).appendTo("#certification");
});
});
};
在document.ready方法中调用getCertifications。 我想根据第一个下拉列表中所选选项的值填充第二个下拉列表。所以我写了另一个函数
var getSpecializations = function () {
var value = $("#certification").val();
$.getJSON("/Provider/GetSpecializations/", { certificationID: value }, function (data) {
$.each(data, function (i, item) {
var specialization_data = "<option value=" + item.SpecializationId + ">" + item.Specialization + "</option>";
$(specialization_data).appendTo("#specialization");
});
});
}
html如图所示
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Certification: </label>
<div class="col-sm-6">
<select class="form-control" id="certification",name="certification",data-bind="value: certification" >
<option value="0">Select a Certification</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Specialization:</label>
<div class="col-sm-6">
<select class="form-control" id="specialization" , name="specialization" data-bind="value: specialization" >
<option value="0">Select a Specialization</option>
</select>
</div>
</div>
我的视图模型具有如图所示的可观察量
self.certification = ko.observable("");
self.specialization = ko.observable("");
我在第一个下拉列表的subscribe方法中调用getSpecializations函数,如此
self.certification.subscribe(function () {
getSpecializations();
});
控制台没有错误,但是第二次下降,即;专业化下拉列表没有填充。你能不能指出我正确的方向。
答案 0 :(得分:1)
你需要这样做
查看:
<select data-bind="options:specializationArray,optionsText:'Specialization',optionsValue:'SpecializationId',value:specialization" />
<强>视图模型:强>
var getSpecializations = function () {
var value = self.
$.getJSON("/Provider/GetSpecializations/", { certificationID: value }, function (data) {
self.specializationArray(data) //array with Specialization and SpecializationId
}
工作小提琴 here