Cascading Dropdown List Using MVC And Web API With Angular 7

In this article, we are going to create a Cascading dropdown list using MVC, Web API, SQL, and Angular 7. Mainly, we will see how to populate state name by country name and display district name by the state, using Angular 7.

In this article, we are going to create a Cascading dropdown list using MVC, Web API, SQL, and Angular 7. Mainly, we will see how to populate state name by country name and display district name by the state, using Angular 7. In some previous articles, we achieved the same functionality using jQuery and AngularJS. Nowadays, there is a demand in the market for Angular's latest version. So now, we will see this example with Angular 7.  You can read my previous articles from the following links.

Creating Tables

In this example, we are taking three tables - Country, State, and District. Here, we will perform cascading using these tables.

Country_Details

  1. CREATE TABLE [dbo].[Country_Details](  
  2.     [Country_Code] [varchar](15) NOT NULL,  
  3.     [Country_Name] [varchar](30) NULL,  
  4. PRIMARY KEY CLUSTERED   
  5. (  
  6.     [Country_Code] ASC  
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  8. ON [PRIMARY]  
  9.   
  10. GO  

State_Details

  1. CREATE TABLE [dbo].[State_Details](  
  2.     [State_Code] [varchar](15) NOT NULL,  
  3.     [State_Name] [varchar](30) NULL,  
  4.     [Country_Code] [varchar](15) NULL,  
  5. PRIMARY KEY CLUSTERED   
  6. (  
  7.     [State_Code] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10.   
  11. GO  

District_Details

  1. CREATE TABLE [dbo].[District_Details](  
  2.     [District_Code] [varchar](15) NOT NULL,  
  3.     [District_Name] [varchar](30) NULL,  
  4.     [Country_Code] [varchar](15) NULL,  
  5.     [State_Code] [varchar](15) NULL,  
  6. PRIMARY KEY CLUSTERED   
  7. (  
  8.     [District_Code] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  

Creating a Web API using MVC

First, we will create an API to bind the Country, State, and District items. Let us see how to create the API.

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

Cascading Dropdown List Using MVC, Web API And Angular 7 

Now, click the OK button.

Cascading Dropdown List Using MVC, Web API And Angular 7 

Select Web API and click OK.

Now, we will add tables in the Web API project using Entity Framework. In this example, we will use the database-first approach. So for this, go to Models folder and right-click -> Add -> New item -> ADO.NET Entity Data Model. Click Add, select EF Designer from the database, and click the "Next" button.

Cascading Dropdown List Using MVC, Web API And Angular 7 

Select "New Connection" and give the connection credentials. Then, select the right database and click OK.

Cascading Dropdown List Using MVC, Web API And Angular 7
 
Cascading Dropdown List Using MVC, Web API And Angular 7 

Check the "Tables" box and click OK.

Cascading Dropdown List Using MVC, Web API And Angular 7
 
Cascading Dropdown List Using MVC, Web API And Angular 7

After that, we will add an API Controller.

Cascading Dropdown List Using MVC, Web API And Angular 7

Select Web API 2 Controller - Empty.

Cascading Dropdown List Using MVC, Web API And Angular 7

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

DemoController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5. using AngularAPI.Models;  
  6.   
  7. namespace AngularAPI.Controllers  
  8. {  
  9.     [RoutePrefix("Api/Demo")]  
  10.     public class DemoController : ApiController  
  11.     {  
  12.         [Route("CountryDetails")]  
  13.         [HttpGet]  
  14.         public List<Country_Details> BindCountry()  
  15.         {  
  16.             IEnumerable<Country_Details> lstCountry = new List<Country_Details>();  
  17.             try  
  18.             {  
  19.                 using (TestDBEntities objEntity = new TestDBEntities())  
  20.                 {  
  21.                     lstCountry = objEntity.Country_Details.ToList();  
  22.   
  23.                 }  
  24.             }  
  25.             catch(Exception)  
  26.             {  
  27.                 throw;  
  28.             }  
  29.              
  30.             return lstCountry.ToList();  
  31.   
  32.         }  
  33.   
  34.         [Route("StateDetails/{counryId}")]  
  35.         [HttpGet]  
  36.         public List<State_Details> BindState(string counryId)  
  37.         {  
  38.             IEnumerable<State_Details> lstState = new List<State_Details>();  
  39.             try  
  40.             {  
  41.                 using (TestDBEntities objEntity = new TestDBEntities())  
  42.                 {  
  43.                     lstState = objEntity.State_Details.Where(a => a.Country_Code == counryId).ToList();  
  44.                 }  
  45.             }  
  46.             catch(Exception)  
  47.             {  
  48.                 throw;  
  49.             }    
  50.             return lstState.ToList();  
  51.   
  52.         }  
  53.   
  54.         [Route("CityDetails/{cityId}")]  
  55.         [HttpGet]  
  56.         public List<District_Details> BindCity(string cityId)  
  57.         {  
  58.             IEnumerable<District_Details> lstDistrict = new List<District_Details>();  
  59.             try  
  60.             {  
  61.                 using (TestDBEntities objEntity = new TestDBEntities())  
  62.                 {  
  63.   
  64.                     lstDistrict = objEntity.District_Details.Where(a => a.State_Code == cityId).ToList();  
  65.                 }  
  66.             }  
  67.             catch(Exception)  
  68.             {  
  69.                 throw;  
  70.             }  
  71.             return lstDistrict.ToList();  
  72.         }  
  73.     }  
  74. }  

Adding Angular Project

We are finished with the API creation. Now, we will create an Angular project. In this example, we are using Angular 7, so first, we will add an Angular project and configure it.

Now, let us create the web application in Angular 7 that will consume that Web API.

First, we have to make sure that we have Angular CLI installed. Open the command prompt and type the below code and press ENTER:

npm install -g @angular/cli

Now, open Visual Studio Code and create a project. Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. We can give the name as BindDropDown.

ng new BindDropDown

After that, hit Enter. It will take a while to create the project.

Once created, the project should look like this.

Cascading Dropdown List Using MVC, Web API And Angular 7

Creating a component

Now, we can create some components to provide UI.

I'm going to create a new component, Country. Go to the TERMINAL and go to the Angular project location using the following command.

cd projectName

Now, write the following command that will create a component.

ng g c country

Press ENTER.

Creating Service

Now, we will create a service in the shared folder. Let us see how to create a service.

Open the Terminal and write the below command.

ng g s shared/common

Creating Model classes

We will create three model classes. Open TERMINAL and write the below command.

  • ng g class model/country --type=model
  • ng g class model/state --type=model
  • ng g class model/city --type=model

We can see the final look after creating all things.

Cascading Dropdown List Using MVC, Web API And Angular 7

Setting properties of Country, State, and City

Now, write all the properties of the classes that match with the database.

country.model.ts

  1. export class Country {  
  2.     Country_Code :string;  
  3.     Country_Name :string;  
  4. }  

state.model.ts

  1. export class State {  
  2.    State_Code : string;  
  3.    State_Name : string;  
  4. }  

city.model.ts

  1. export class City {  
  2.     District_Code : string;  
  3.     District_Name : string;  
  4. }  

Now, open common.service.ts and first, import necessary classes and libraries and then, make calls to the Web API methods. 

  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { Country } from '../model/country.model';  
  4. import { State } from '../model/state.model';  
  5. import { City } from '../model/city.model';  
  6.   
  7. @Injectable({  
  8.   providedIn: 'root'  
  9. })  
  10. export class CommonService {  
  11.   readonly url = 'http://localhost:50707/Api/Demo/';  
  12.   listCountry : Country[];  
  13.   listState: State[];  
  14.   listCity: City[];  
  15.   constructor(private http: HttpClient) { }  
  16.   
  17.   CountryList() {  
  18.     this.http.get(this.url + 'CountryDetails').toPromise().then(result=>this.listCountry = result as Country[])  
  19.   }  
  20.   
  21.   StateByCountry(countryID:string) {  
  22.    return this.http.get(this.url + 'StateDetails/' + countryID).toPromise().then(result=>this.listState = result as State[])  
  23.   }  
  24.     
  25.   DistrictByState(stateID:string) {  
  26.     return this.http.get(this.url + 'CityDetails/' + stateID).toPromise().then(result=>this.listCity = result as City[])  
  27.    }  
  28. }  

Component

Now, open country.component.ts file and write below code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { CommonService } from '../shared/common.service';  
  3. @Component({  
  4.    selector: 'app-country',  
  5.    templateUrl: './country.component.html',  
  6.    styleUrls: ['./country.component.css']  
  7. })  
  8. export class CountryComponent implements OnInit {  
  9.    constructor(private service:CommonService) {  
  10. }  
  11. ngOnInit() {  
  12.    this.service.CountryList();  
  13. }  
  14. BindState(countryId : string){  
  15.    this.service.StateByCountry(countryId);  
  16. }  
  17. BindCity(stateId : string){  
  18.    this.service.DistrictByState(stateId);  
  19.    }  
  20. }   
Design HTML

Let us design our HTML page now. Open country.component.html and write the following HTML code.

  1. <div class="container">  
  2.     <br>  
  3.     <h2>Cascading Dropdownlist Example in Angular 7</h2>  
  4.     <hr>  
  5.     <br>  
  6.     <div class="row">  
  7.     <div class="col-md-2">  
  8.             <label>Country Name</label>  
  9.     </div>  
  10.     <div class="col-md-6">  
  11.         
  12.     <select name="Country"  (change)="BindState($event.target.value)" class="form-control">  
  13.         <option value="undefined">Select Country Name</option>  
  14.         <option *ngFor="let country of service.listCountry" [value]="country.Country_Code">  
  15.             {{country.Country_Name}}  
  16.         </option>  
  17.     </select>  
  18.      
  19. </div>  
  20. </div>  
  21. <div class="row">  
  22.     <div class="col-md-2">  
  23.             <label>State Name</label>  
  24.     </div>  
  25.     <div class="col-md-6">     
  26.      
  27.   
  28.     <select name="State"  class="form-control" (change)="BindCity($event.target.value)">  
  29.         <option value="undefined">Select State Name</option>  
  30.         <option *ngFor="let country of service.listState" [value]="country.State_Code">  
  31.             {{country.State_Name}}  
  32.         </option>  
  33.     </select>  
  34. </div>  
  35. </div>  
  36.   
  37. <div class="row">  
  38.     <div class="col-md-2">  
  39.             <label>State Name</label>  
  40.     </div>  
  41.     <div class="col-md-6">  
  42.     <select name="City"  class="form-control">  
  43.         <option value="undefined">Select City Name</option>  
  44.         <option *ngFor="let city of service.listCity" [value]="city.District_Code">  
  45.             {{city.District_Name}}  
  46.         </option>  
  47.     </select>  
  48. </div>  
  49. </div>  
  50. </div>  

Now, let's add all required libraries in app.module.ts. Open the app.module.ts class and write the below code.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import{HttpClientModule} from '@angular/common/http';  
  7. import { CountryComponent } from './country/country.component';  
  8. import { CommonService } from './shared/common.service';  
  9.   
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,  
  13.     CountryComponent  
  14.   ],  
  15.   imports: [  
  16.     BrowserModule,  
  17.     AppRoutingModule,  
  18.     HttpClientModule  
  19.   ],  
  20.   providers: [CommonService],  
  21.   bootstrap: [AppComponent]  
  22. })  
  23. export class AppModule { }  

Setting app.component.ts

Open app.component.html and write the below code.

  1. <div  class="container">  
  2.   <app-country></app-country>  
  3. </div>  

Setting Index.html

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>BindDropDown</title>  
  6.   <base href="/">  
  7.   
  8.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  10.   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">  
  11. </head>  
  12. <body>  
  13.   <app-root></app-root>  
  14.   
  15. </body>  
  16. </html>  

We have completed all the needed coding. Before running the application, make sure to save your work.

If you consume the Web API, Angular blocks the URL and we call this issue CORS (Cross-Origin Resource Sharing). So first, check if CORS is installed or not. If not, then let us install CORS in the API.

Go to the Web API project. 

Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.

Cascading Dropdown List Using MVC, Web API And Angular 7 

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

Add Namespace,

  1. using System.Web.Http.Cors;  

And write the below code inside the Register method.

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

Run the project

Now, let's run the app and see how it works. 

Open TERMINAL and write the following command to run the program.

ng serve -o

Now, let us see the output.

Cascading Dropdown List Using MVC, Web API And Angular 7
 
Cascading Dropdown List Using MVC, Web API And Angular 7 
 
We've finished a cascading dropdown list example in Angular7 using Web API functionality. The app uses a Web API to provide data access from SQL Server. 

Thank you for reading my article.