Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascading drop down with KNOCKOUT.JS & ASP.NET MVC 4

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.

like image 320
sergej.art Avatar asked Feb 13 '13 09:02

sergej.art


1 Answers

<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>
like image 173
Ruslan Avatar answered Oct 12 '22 04:10

Ruslan