Magic of knockoutjs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Country = new SelectList(Country.GetCountryList(), "Code", "Name");
return View();
}
public ActionResult GetStates(string id = "")
{
var stateList = State.GetStates()
.Where(s => s.CountryCode.ToLower() == id.ToLower());
return this.Json(stateList, JsonRequestBehavior.AllowGet);
}
}
// State model class
// Property of State class is used to
// bind view with knockoutjs viewmodel
public class State
{
public string CountryCode { get; set; }
public int StateId { get; set; }
public string StateName { get; set; }
}
<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>
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);
});
}
Add comment