i on update details screen , have country , state dropdown .i want pre populate state dropdown on basis of selected country. on initial page load have selected country,country collection , selected state need fetch 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 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> but when try fetch state list through ajax request selected state value gets reset , first value in list becomes default selected value. confused, why ko update selected state value when not changing @ all?
but if set selected state again in ajax success callback 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 looking reason strange behavior.
i have tried simplifying code directed , think might point out 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>
Comments
Post a Comment