Cascading Dropdownlist in ASP.Net MVC4 using KnockoutJS

In this article, we are going to see the implementation of Cascading Dropdownlist in ASP.Net MVC4 using KnockoutJS. KnockoutJS is a JavaScript library that helps us in responsive display of the UI. Let’s go through the implementation, Create an ASP.Net MVC4 Internet Web application and Add the following State.cs and City.cs Classes in Models folder of the application.

State.cs-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDropDownKOjs.Models
{
    public class State
    {
        public string Code { get; set; }
        public string Name { get; set; }

        public static List<State> GetStateList()
        {
            return new List<State> { 
                new State{ Code="AP",Name="Andhra Pradesh"},
                new State{ Code="KA",Name="Karnataka"},
                new State{ Code="MH",Name="Maharashtra"}
            };
        }
    }
}

City.cs-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDropDownKOjs.Models
{
    public class City
    {
        public string StateCode { get; set; }
        public int CityId { get; set; }
        public string CityName { get; set; }

        public static List<City> GetCityList()
        {
            int id = 0;
            return new List<City> { 
                new City{ StateCode="AP",CityId=id++,CityName="Hyderabad"},
                new City{ StateCode="AP",CityId=id++,CityName="Vizag"},
                new City{ StateCode="AP",CityId=id++,CityName="Vijayawada"},
                new City{ StateCode="KA",CityId=id++,CityName="Bangalore"},
                new City{ StateCode="KA",CityId=id++,CityName="Mysore"},
                new City{ StateCode="MH",CityId=id++,CityName="Mumbai"},
                new City{ StateCode="MH",CityId=id++,CityName="Pune"}
            };
        }
    }
}

 

Change the Index() and add GetCities() in HomeController.cs Class file as shown below.

HomeController.cs-

using CascadingDropDownKOjs.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CascadingDropDownKOjs.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.State= new SelectList(State.GetStateList(), 
                                          "Code","Name");
            return View();
        }

        public JsonResult GetCities(string code)
        {
            var cityList = City.GetCityList()
                 .Where(s => s.StateCode.ToLower() == code.ToLower());
            return this.Json(cityList,JsonRequestBehavior.AllowGet);
        }
    }
}

And add the following markup in index.cshtml file.

index.cshtml-

<p>
<b>Select State :</b>
     @Html.DropDownList("ddlState",
                        ViewBag.State as SelectList, 
                        "Choose...", 
                        new { onchange = "FetchCities();" })
</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>

Also,add the following script in index.cshtml file.

index.cshtml-

<script type='text/javascript'>
    //Creating ViewModel for the Cities Dropdown List
function CascadingDDLViewModel() {
  this.cities = ko.observableArray([]);
}
    //Creating an object for VieModel and applying bindings to the View
var objVM = new CascadingDDLViewModel();
ko.applyBindings(objVM);
//This function will be called onchange of State Dropdown List
function FetchCities() {
    var stateCode = $("#ddlState").val();
    $.getJSON("/Home/GetCities?code="+ stateCode, null, function (data) {
    objVM.cities(data);
  });
}
</script>

By default when we created an ASP.Net MVC4 Internet application the KnockoutJS libraries will be added in the Scripts folder of the application.We need to register those libraries to the Bundles Collection by adding the following line to RegisterBundles method of BundleConfig.cs class file.

BundleConfig.cs-

using System.Web;
using System.Web.Optimization;

namespace CascadingDropDownKOjs
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            //Already Registered Bundles
            //---
            //---
            //Add here
            bundles.Add(new ScriptBundle("~/bundles/Knockout").Include(
                       "~/Scripts/Knockout-*"));
        }
    }
}

Now Run the application by pressing Ctrl+F5.And select a State in the State Dropdownlist,the Cities Dropdownlist will be populated with available cities for that State.

csdknockout

Happy Coding!!!

You may also like...