级联下拉prepopulate淘汰赛MVC [英] cascaded dropdown prepopulate knockout MVC
问题描述
我更新详情屏幕上,我有一个国家和。我想要的状态下拉至pre填充国家下拉列表中选择的国家的基础上。 在初始页面加载我有选择的国家,国家收集和选定状态的所有我需要的是使用AJAX来获取国家收藏。
I am on the Update details screen and I have a Country and a state dropdown .I want to pre populate State dropdown on the basis of the selected Country. On the initial page load I do have the selected Country,Country Collection and Selected State all I need is to fetch the State Collection using AJAX.
Country List: <select id="CountryDropdownList" data-bind="options: viewModel.CountryCollection,optionsText:'CountryName',optionsValue:'CountryName',value:viewModel.SelectedCountry"></select>
State List: <select id="StateDropdownList" data-bind="options: viewModel.StateCollection,optionsText:'StateName',optionsValue:'StateName',value:viewModel.SelectedState"></select>
<script>
var viewModel = ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); //State3 the initial value
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
console.log(viewModel.SelectedState()); //undefined why?
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); //state0 why?
}
})
});
ko.applyBindings(viewModel);
$(function () {
viewModel.SelectedCountry.valueHasMutated();
})
</script>
但是,当我尝试获取通过AJAX请求状态列表中选择状态值被复位,并在列表中的第一个值将成为缺省选择的值。我很困惑,为什么KO更新我的选中状态值时,我不改变它呢?
But when I try to fetch the state list through AJAX request the Selected State value gets reset and the first value in the list becomes the default selected value. I am confused, why does KO update my selected State value when I am not changing it at all?
但是,如果我在AJAX回调的成功再次设置选中状态正常工作
But if I set the Selected State again in AJAX Success callback it works fine
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data.StateCollection)());
viewModel.SelectedState(data.SelectedState);
}
})
});
我要寻找一个理由奇怪的行为。
I am looking for a reason for this strange behavior.
推荐答案
我试图简化了code作为导演你,现在我想这可能会帮助你指出的问题。
I have tried simplifying the code as directed by you and now I think it might help you to point out the issue.
<script>
var viewModel = ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); // o/p state3
$.ajax({
url: 'Home/GetStateList?Country=' + viewModel.SelectedCountry(),
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); // o/p state0
}
})
ko.applyBindings(viewModel);
</script>
这篇关于级联下拉prepopulate淘汰赛MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!