Cascading DropDown in MVC4 Using Knockout, Web API With Entity Framework

In this article, I will explore many things, including dropdown cascading, how to use Entity Framework and how to use a data transfer object with Entity Framework and how to use the ASP.NET Web API and fetch data using the ASP.NET Web API and display using Knockout.

Web API

The ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. The ASP.NET Web API is an ideal platform for building REST applications on the .NET Framework.

Knockout

Knockout is a JavaScript library that helps you to create rich, responsive displays and editor user interfaces with a clean underlying data model. Read more here: knockoutjs.

Entity Framework

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Data Transfer Objects

Data Transfer Objects are reusable classes that contain related data and no business logic. They may be defined on the service side, client side, or both sides of the communication channel. Their properties (in other words getters/setters) may wrap primitive data types (for example integers, strings, and so on) or other DTOs.

Getting Started

  • Create a new Project. Open Visual Studio 2012.
  • Go to "File" -> "New" -> "Project...".
  • Select "Web" in the installed templates.
  • Select "ASP.NET MVC 4 Web Application".
  • Enter the Name and choose the location.
  • Click "OK".

This is my database schema that is used in this sample:

database schema

As you all know when we use the Entity Framework it builds default model classes and context classes, so we will use a data transfer object besides using Entity Framework models and context classes.

So first of all add data transfer object model classes:
  1. public class CountryDTO  
  2. {  
  3.     public int CountryId { getset; }  
  4.     public string CountryName { getset; }  
  5. }  
  6. public class StateDTO  
  7. {  
  8.     public int StateId { getset; }  
  9.     public int CountryId { getset; }  
  10.     public string StateName { getset; }  
  11. }  
  12. public class CityDTO  
  13. {  
  14.      public int StateId { getset; }  
  15.      public int CityId { getset; }  
  16.      public string CityName { getset; }  
  17. } 

Now add a converter class as in the following:

  1. public static class Converter  
  2. {  
  3.     public static CountryDTO CountriesToCountryDTO(Countries e)  
  4.     {  
  5.         return new CountryDTO  
  6.         {  
  7.             CountryId = e.CountryId,  
  8.             CountryName = e.CountryName  
  9.         };  
  10.     }  
  11.     public static List<CountryDTO> LCountriesToCountryDTO(List<Countries> e)  
  12.     {  
  13.         List<CountryDTO> lstCountryDTO = e.Select(  
  14.           country => new CountryDTO()  
  15.           {  
  16.               CountryId = country.CountryId,  
  17.               CountryName = country.CountryName  
  18.           }).ToList();  
  19.         return lstCountryDTO;  
  20.     }  
  21.     public static StateDTO StatesToStateDTO(States e)  
  22.     {  
  23.         return new StateDTO  
  24.         {  
  25.             StateId = e.StateId,  
  26.             StateName = e.StateName  
  27.         };  
  28.     }  
  29.     public static List<StateDTO> LStatesToStateDTO(List<States> e)  
  30.     {  
  31.         List<StateDTO> lstStateDTO = e.Select(  
  32.          state => new StateDTO()  
  33.          {  
  34.              StateId = state.StateId,  
  35.              StateName = state.StateName  
  36.          }).ToList();  
  37.         return lstStateDTO;  
  38.     }  
  39.     public static CityDTO CitiesToCityDTO(Cities e)  
  40.     {  
  41.         return new CityDTO  
  42.         {  
  43.             CityId = e.CityId,  
  44.             CityName = e.CityName  
  45.         };  
  46.     }  
  47.     public static List<CityDTO> LCitiesToCityDTO(List<Cities> e)  
  48.     {  
  49.         List<CityDTO> lstCityDTO = e.Select(  
  50.          city => new CityDTO()  
  51.          {  
  52.              CityId = city.CityId,  
  53.              CityName = city.CityName  
  54.          }).ToList();  
  55.         return lstCityDTO;  
  56.     }  
  57. } 

Here is my repository class:

  1. public class LocationRepository : ILocationRepository  
  2. {  
  3.     public List<CountryDTO> GetCountries()  
  4.     {  
  5.         using (TestDBEntities dbcontext1 = new TestDBEntities())  
  6.         {  
  7.             var lstCountries = from r in dbcontext1.Countries select r;  
  8.             List<CountryDTO> lst = new List<CountryDTO>();  
  9.             lst = Converter.LCountriesToCountryDTO(lstCountries.ToList());  
  10.             return lst;  
  11.         }  
  12.     }  
  13.     public List<StateDTO> GetStates(int countryId)  
  14.     {  
  15.         using (TestDBEntities dbcontext = new TestDBEntities())  
  16.         {  
  17.             var lstStates = dbcontext.States.Where(b => b.CountryId == countryId).ToList();  
  18.             List<StateDTO> list = new List<StateDTO>();  
  19.             list = Converter.LStatesToStateDTO(lstStates.ToList());  
  20.             return list;  
  21.         }  
  22.     }  
  23.     public List<CityDTO> GetCities(int stateId)  
  24.     {  
  25.         using (TestDBEntities dbcontext = new TestDBEntities())  
  26.         {  
  27.             var lstCities = dbcontext.Cities.Where(b => b.StateId == stateId).ToList();  
  28.             List<CityDTO> list = new List<CityDTO>();  
  29.             list = Converter.LCitiesToCityDTO(lstCities.ToList());  
  30.             return list;  
  31.         }  
  32.     }  
  33. } 

Repository interface

  1. public interface ILocationRepository  
  2. {  
  3.     List<CountryDTO> GetCountries();  
  4.     List<StateDTO> GetStates(int countryId);  
  5.     List<CityDTO> GetCities(int stateId);  
  6. } 

Now add a Web API controller class:



This is my controller class code:

  1. public class LocationController : ApiController  
  2. {  
  3.     static readonly ILocationRepository repository = new LocationRepository();   
  4.     // GET api/<controller>          
  5.     public IEnumerable<CountryDTO> GetCountries()  
  6.     {  
  7.         //return new string[] { "value1", "value2" };  
  8.         return repository.GetCountries();  
  9.     }  
  10.     // GET api/<controller>/5   
  11.     [ActionName("GetStates")]  
  12.     public IEnumerable<StateDTO> GetStates(int id)  
  13.     {  
  14.         return repository.GetStates(id);  
  15.     }  
  16.     // GET api/<controller>/5      
  17.     [ActionName("GetCities")]  
  18.     public IEnumerable<CityDTO> GetCities(int id)  
  19.     {  
  20.         return repository.GetCities(id);  
  21.     }   
  22.     // POST api/<controller>  
  23.     public void Post([FromBody]string value)  
  24.     {  
  25.     }   
  26.     // PUT api/<controller>/5  
  27.     public void Put(int id, [FromBody]string value)  
  28.     {  
  29.     }   
  30.     // DELETE api/<controller>/5  
  31.     public void Delete(int id)  
  32.     {  
  33.     }  
  34. } 

To stop method conflics we have added an ActionName to two methods.

Now add this routing to the WebApiConfig class:

  1. public static void Register(HttpConfiguration config)  
  2. {  
  3.     config.Routes.MapHttpRoute(  
  4.     name: "DefaultApi",  
  5.     routeTemplate: "api/{controller}/{id}",  
  6.     defaults: new { id = RouteParameter.Optional }  
  7.   );  
  8.     config.Routes.MapHttpRoute(  
  9.      name: "DefaultApiWithAction",  
  10.      routeTemplate: "api/{controller}/{action}/{id}",  
  11.      defaults: new { id = RouteParameter.Optional }  
  12.    );  
  13. } 

Here we are done with the model and controller parts, now time to work on the view part.

  1. @{  
  2.     ViewBag.Title = "Cascading DropDown using Knockout / WebAPI Sample";  
  3. }  
  4. <script src="~/Scripts/jquery-1.8.2.min.js"></script>  
  5. <script src="~/Scripts/knockout-2.2.0.js"></script>  
  6.  <script type="text/javascript">         
  7.         $(document).ready(function () {  
  8.             FetchCountries();  
  9.             $("#Country").change(function () {  
  10.                 var countryId = $("#Country").val();  
  11.                 $.ajax({  
  12.                     type: "GET",  
  13.                     url: "http://localhost:62830/api/Location/GetStates/" + countryId,  
  14.                     contentType: "application/json; charset=utf-8",  
  15.                     dataType: "json",  
  16.                     success: function (response) {  
  17.                         if (response != "") {  
  18.                             $(response).each(function (index, element) {  
  19.                                 viewModel.stateCollection.push(element);  
  20.                             });  
  21.                             ko.applyBindings(viewModel);  
  22.                         }  
  23.                     }  
  24.                 });  
  25.             });  
  26.             $("#State").change(function () {  
  27.                 var stateId = $("#State").val();  
  28.                 $.ajax({  
  29.                     type: "GET",  
  30.                     url: "http://localhost:62830/api/Location/GetCities/" + stateId,  
  31.                     contentType: "application/json; charset=utf-8",  
  32.                     dataType: "json",  
  33.                     success: function (response) {  
  34.                         if (response != "") {  
  35.                             $(response).each(function (index, element) {  
  36.                                 viewModel.cityCollection.push(element);  
  37.                             });  
  38.                             ko.applyBindings(viewModel);  
  39.                         }  
  40.                     }  
  41.                 });  
  42.             });  
  43.         });  
  44.         function FetchCountries() {  
  45.             viewModel = {  
  46.                 countryCollection: ko.observableArray(),  
  47.                 stateCollection: ko.observableArray(),  
  48.                 cityCollection: ko.observableArray()  
  49.             };  
  50.             $.ajax({  
  51.                 type: "GET",  
  52.                 url: "http://localhost:62830/api/Location",  
  53.                 contentType: "application/json; charset=utf-8",  
  54.                 dataType: "json",  
  55.                 success: function (response) {  
  56.                     if (response != "") {  
  57.                         $(response).each(function (index, element) {  
  58.                             viewModel.countryCollection.push(element);  
  59.                         });  
  60.                         ko.applyBindings(viewModel);  
  61.                     }  
  62.                 }  
  63.             });  
  64.         }  
  65.     </script>  
  66. <h2>Cascading DropDown using Knockout / WebAPI Sample</h2>  
  67.  Country Name: <select data-bind="options: countryCollection, optionsCaption: 'Choose country...',  
  68.     optionsValue: function (item) { return item.CountryId; },  
  69.     optionsText: function (item) { return item.CountryName; }, value: Country,  
  70.     valueUpdate: 'change'" id="Country" name="Country"></select>  
  71. <br />  
  72. State Name: <select data-bind="options: stateCollection, optionsCaption: 'Choose state...',  
  73.     optionsValue: function (item) { return item.StateId; },  
  74.     optionsText: function (item) { return item.StateName; },  value: State,  
  75.     valueUpdate: 'change'" id="State" name="State"></select>  
  76. <br />  
  77. City Name: <select data-bind="options: cityCollection, optionsCaption: 'Choose city...',  
  78.     optionsValue: function (item) { return item.CityId; },  
  79.     optionsText: function (item) { return item.CityName; }, value: City,  
  80.     valueUpdate: 'change'" id="City" name="City"></select> 

All set. Now run the application as in the following:
run the application

 
Select State
 
Select City 


Similar Articles