I am following this tutorial:
http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html
The project provided works like a charm. It may be downloaded from here: http://files.dotnetexpertguide.com/download.aspx?key=cascadingddlknockoutjs
The question is - I can't figure out how to change the View, so that one more City select box appears and its content changes according to the State selected?
Writing one more model for the city and action in controller for fetching cities by State Id is pretty straight forward, but I don't understand how to change the View and JS code so it works.
So the code for the View:
<p>
<b>Select Country :</b> @Html.DropDownList("ddlCountry", ViewBag.Country as SelectList,"Select...", new { onchange = "FetchStates();" })
</p>
<p data-bind="visible: states().length > 0">
<b>Select State :</b> <select data-bind="options: states, optionsText: 'StateName', optionsValue: 'StateId', optionsCaption: 'Choose...'"></select>
</p>
<script type='text/javascript'>
function CascadingDDLViewModel() {
this.states = ko.observableArray([]);
}
var objVM = new CascadingDDLViewModel();
ko.applyBindings(objVM);
function FetchStates() {
var countryCode = $("#ddlCountry").val();
$.getJSON("/Home/GetStates/" + countryCode, null, function (data) {
objVM.states(data);
});
}
</script>
Any help is very appreciated.
<p>
<b>Select Country :</b> @Html.DropDownList("ddlCountry", ViewBag.Country as SelectList,"Select...", new { onchange = "FetchStates();" })
</p>
<p data-bind="visible: states().length > 0">
<b>Select State :</b> <select id="ddlStates" data-bind="options: states, optionsText: 'StateName', optionsValue: 'StateId', optionsCaption: 'Choose...'"></select>
</p>
<p data-bind="visible: cities().length > 0">
<b>Select City :</b> <select data-bind="options: cities, optionsText: 'CityName', optionsValue: 'CityId', optionsCaption: 'Choose...'"></select>
</p>
<script type='text/javascript'>
function CascadingDDLViewModel() {
this.states = ko.observableArray([]);
this.cities = ko.observableArray([]);
}
var objVM = new CascadingDDLViewModel();
ko.applyBindings(objVM);
function FetchStates() {
var countryCode = $("#ddlCountry").val();
$.getJSON("/Home/GetStates/" + countryCode, null, function (data) {
objVM.states(data);
});
function FetchCities() {
var stateId = $("#ddlStates").val();
$.getJSON("/Home/GetCities/" + stateId, null, function (data) {
objVM.cities(data);
});
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With