Cascading Dropdown List Of Country, State And City Using MVC, Web API And jQuery

Today, in this article, I will explain how to create a cascading dropdown list using MVC, Web API, and jQuery. Here, I am using three tables - Country, State, and City - respectively. If we select a country, then it should display country related states and when we select a state, it should display state-related cities. Finally, here, we will use MVC, Web, jQuery, and SQL Server. So now, let us see the required steps.

Step 1

We have to create three tables - Country, State, and City.
MVC

Step2

Now, we need to create an MVC application but we will create two projects here - one is Web API project for the creation of service and the other one is MVC project for consuming that service. So now, let us add the first MVC project.

Open Visual Studio and go to File->New ->Web application ->select MVC ->OK.

MVC

Step 3

Now, add tables in web API project using Entity Framework. So for  this, go to Models folder ->right-click -> Add -> New item -> ADO.NET Entity Data Model -> click Add -> select database first approach->click Next.

Select "New Connection" and give the connection details, then select database -> click OK.

Choose tables and click OK.

MVC

Step 4

Now, we will write the logic for binding the Country, State and City, So, I create a folder Business Logic and take a class CascadingLogic.cs and write the logic.

MVC
  1. public class CascadingLogic  
  2.  {  
  3.      JobPortalEntities dbEntity = new JobPortalEntities();  
  4.   
  5.      public List<Country> BindCountry()  
  6.      {  
  7.         this.dbEntity.Configuration.ProxyCreationEnabled = false;  
  8.   
  9.          List<Country> lstCountry = new List<Country>();  
  10.          try  
  11.          {  
  12.              lstCountry = dbEntity.Countries.ToList();  
  13.          }  
  14.          catch (Exception ex)  
  15.          {  
  16.              ex.ToString();  
  17.          }  
  18.          return lstCountry;  
  19.      }  
  20.   
  21.      public List<State> BindState(int countryId)  
  22.      {  
  23.          List<State> lstState = new List<State>();  
  24.          try  
  25.          {  
  26.              this.dbEntity.Configuration.ProxyCreationEnabled = false;  
  27.   
  28.              lstState = dbEntity.States.Where(a => a.CountryId == countryId).ToList();  
  29.          }  
  30.          catch (Exception ex)  
  31.          {  
  32.              ex.ToString();  
  33.          }  
  34.          return lstState;  
  35.      }  
  36.   
  37.      public List<City> BindCity(int stateId)  
  38.      {  
  39.          List<City> lstCity = new List<City>();  
  40.          try  
  41.          {  
  42.              this.dbEntity.Configuration.ProxyCreationEnabled = false;  
  43.   
  44.              lstCity = dbEntity.Cities.Where(a => a.StateId == stateId).ToList();  
  45.          }  
  46.          catch (Exception ex)  
  47.          {  
  48.              ex.ToString();  
  49.          }  
  50.          return lstCity;  
  51.      }  
  52.  }  

After that, we will add an API Controller.

MVC

Now, create the API methods and call the methods one by one.

  1. [RoutePrefix("api/Cascading")]  
  2.   public class CascadingDetailsController : ApiController  
  3.   {  
  4.       CascadingLogic objCasc = new CascadingLogic();  
  5.       [HttpGet]  
  6.       [Route("CountryDetails")]  
  7.       public List<Country> BindCountryDetails()  
  8.       {  
  9.   
  10.   
  11.           List<Country> countryDetail = new List<Country>();  
  12.           try  
  13.           {  
  14.               countryDetail = objCasc.BindCountry();  
  15.           }  
  16.           catch (ApplicationException ex)  
  17.           {  
  18.               throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  19.           }  
  20.           catch (Exception ex)  
  21.           {  
  22.               throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  23.           }  
  24.   
  25.           return countryDetail;  
  26.       }  
  27.   
  28.       [HttpGet]  
  29.       [Route("StateDetails")]  
  30.       public List<State> BindStateDetails(int CountryId)  
  31.       {  
  32.   
  33.           List<State> stateDetail = new List<State>();  
  34.           try  
  35.           {  
  36.               stateDetail = objCasc.BindState(CountryId);  
  37.           }  
  38.           catch (ApplicationException ex)  
  39.           {  
  40.               throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  41.           }  
  42.           catch (Exception ex)  
  43.           {  
  44.               throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  45.           }  
  46.   
  47.           return stateDetail;  
  48.       }  
  49.   
  50.       [HttpGet]  
  51.       [Route("CityDetails")]  
  52.       public List<City> BindCityDetails(int stateId)  
  53.       {  
  54.           List<City> cityDetail = new List<City>();  
  55.           try  
  56.           {  
  57.               cityDetail = objCasc.BindCity(stateId);  
  58.           }  
  59.           catch (ApplicationException ex)  
  60.           {  
  61.               throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  62.           }  
  63.           catch (Exception ex)  
  64.           {  
  65.               throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  66.           }  
  67.   
  68.           return cityDetail;  
  69.       }  
  70.   
  71.   }  

Step 5

Now, let's go in MVC project and add a Controller.

MVC

After that, create an action method for View and View page.

  1. public ActionResult Details()  
  2.         {  
  3.             return View();  
  4.         }  

NOTE

Here, we will not consume the API service using server side, we directly use the client side.

Step 6

Now, we design the page using HTML for cascading Country, State, and City.

  1. <h1>Cascading Dropdown List of Country, State and City</h1>  
  2. <hr />  
  3. <br />  
  4. <div class="row">  
  5.     <div class="col-lg-3"></div>  
  6.     <div class="col-lg-6">  
  7.   
  8.         <div class="form-group">  
  9.             <label class="col-md-4 control-label">Country Name</label>  
  10.             <div class="col-md-6">  
  11.                 <select class="form-control" id="ddlCountry"></select><br />  
  12.             </div>  
  13.         </div>  
  14.   
  15.         <div class="form-group">  
  16.             <label class="col-md-4 control-label">State Name</label>  
  17.             <div class="col-md-6">  
  18.                 <select class="form-control" id="ddlState"></select>  
  19.                 <br />  
  20.   
  21.             </div>  
  22.         </div>  
  23.         <br />  
  24.         <div class="form-group">  
  25.             <label class="col-md-4 control-label">City Name</label>  
  26.             <div class="col-md-6">  
  27.                 <select class="form-control" id="ddlCity"></select>  
  28.   
  29.             </div>  
  30.         </div>  
  31.     </div>  
  32.     <div class="col-lg-3"></div>  
  33. </div>  

Output Design

MVC

Now, write the jQuery code for consuming and binding the details.

  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  2. <script>  
  3.     $(document).ready(function () {  
  4.   
  5.         var ddlCountry = $('#ddlCountry');  
  6.         ddlCountry.append($("<option></option>").val('').html('Please Select Country'));  
  7.         $.ajax({  
  8.             url: 'http://localhost:54188/api/Cascading/CountryDetails',  
  9.             type: 'GET',  
  10.             dataType: 'json',  
  11.             success: function (d) {  
  12.                 $.each(d, function (i, country) {  
  13.                     ddlCountry.append($("<option></option>").val(country.CountryId).html(country.CountryName));  
  14.                 });  
  15.             },  
  16.             error: function () {  
  17.                 alert('Error!');  
  18.             }  
  19.         });  
  20.   
  21.         //State details by country id  
  22.   
  23.         $("#ddlCountry").change(function () {  
  24.             var CountryId = parseInt($(this).val());  
  25.   
  26.             if (!isNaN(CountryId)) {  
  27.                 var ddlState = $('#ddlState');  
  28.                 ddlState.empty();  
  29.                 ddlState.append($("<option></option>").val('').html('Please wait ...'));  
  30.   
  31.                 debugger;  
  32.                 $.ajax({  
  33.                     url: 'http://localhost:54188/api/Cascading/StateDetails',  
  34.                     type: 'GET',  
  35.                     dataType: 'json',  
  36.                     data: { CountryId: CountryId },  
  37.                     success: function (d) {  
  38.   
  39.                         ddlState.empty(); // Clear the please wait  
  40.                         ddlState.append($("<option></option>").val('').html('Select State'));  
  41.                         $.each(d, function (i, states) {  
  42.                             ddlState.append($("<option></option>").val(states.StateId).html(states.StateName));  
  43.                         });  
  44.                     },  
  45.                     error: function () {  
  46.                         alert('Error!');  
  47.                     }  
  48.                 });  
  49.             }  
  50.   
  51.   
  52.         });  
  53.   
  54.         //City Bind By satate id  
  55.         $("#ddlState").change(function () {  
  56.             var StateId = parseInt($(this).val());  
  57.             if (!isNaN(StateId)) {  
  58.                 var ddlCity = $('#ddlCity');  
  59.                 ddlCity.append($("<option></option>").val('').html('Please wait ...'));  
  60.   
  61.                 debugger;  
  62.                 $.ajax({  
  63.                     url: 'http://localhost:54188/api/Cascading/CityDetails',  
  64.                     type: 'GET',  
  65.                     dataType: 'json',  
  66.                     data: { stateId: StateId },  
  67.                     success: function (d) {  
  68.   
  69.   
  70.                         ddlCity.empty(); // Clear the plese wait  
  71.                         ddlCity.append($("<option></option>").val('').html('Select City Name'));  
  72.                         $.each(d, function (i, cities) {  
  73.                             ddlCity.append($("<option></option>").val(cities.CityId).html(cities.CityName));  
  74.                         });  
  75.                     },  
  76.                     error: function () {  
  77.                         alert('Error!');  
  78.                     }  
  79.                 });  
  80.             }  
  81.   
  82.   
  83.         });  
  84.     });  
  85. </script>  

Let us run the project but we have to run both projects at one time so for this, so we have to set some changes.

Right-click on the solution project and go to properties. There, check the "Multiple startup projects" option and click "Apply".

MVC

Now, we can see the output. It is not giving the expected result but some error.

MVC
This error is called CORS. So first, we have to know what CORS is and how to resolve this problem.

According to Wikipedia,

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.

For more details click this link.

Now, let us learn how to resolve this problem.

So for this, we have to download CORS in Web API project. Go to NuGet Package Manager and download the following file.

MVC

After that, goto App_Start folder in Web API project and then WebApiConfig.cs class. Here, modify the Register method with the below code.

  1. var cors = new EnableCorsAttribute("*""*""*");// origins, headers, methods  
  2. config.EnableCors(cors);  

Now, save changes and run the project to see the final output.

Select a country

MVC

Select a state

MVC

Thanks! I hope this article was helpful.