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
- CREATE TABLE [dbo].[Country_Details](
- [Country_Code] [varchar](15) NOT NULL,
- [Country_Name] [varchar](30) NULL,
- PRIMARY KEY CLUSTERED
- (
- [Country_Code] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
State_Details
- CREATE TABLE [dbo].[State_Details](
- [State_Code] [varchar](15) NOT NULL,
- [State_Name] [varchar](30) NULL,
- [Country_Code] [varchar](15) NULL,
- PRIMARY KEY CLUSTERED
- (
- [State_Code] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
District_Details
- CREATE TABLE [dbo].[District_Details](
- [District_Code] [varchar](15) NOT NULL,
- [District_Name] [varchar](30) NULL,
- [Country_Code] [varchar](15) NULL,
- [State_Code] [varchar](15) NULL,
- PRIMARY KEY CLUSTERED
- (
- [District_Code] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) 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.
Now, click the OK button.
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.
Select "New Connection" and give the connection credentials. Then, select the right database and click OK.
Check the "Tables" box and click OK.
After that, we will add an API Controller.
Select Web API 2 Controller - Empty.
Now, create the API methods and call the methods one by one.
DemoController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- using AngularAPI.Models;
-
- namespace AngularAPI.Controllers
- {
- [RoutePrefix("Api/Demo")]
- public class DemoController : ApiController
- {
- [Route("CountryDetails")]
- [HttpGet]
- public List<Country_Details> BindCountry()
- {
- IEnumerable<Country_Details> lstCountry = new List<Country_Details>();
- try
- {
- using (TestDBEntities objEntity = new TestDBEntities())
- {
- lstCountry = objEntity.Country_Details.ToList();
-
- }
- }
- catch(Exception)
- {
- throw;
- }
-
- return lstCountry.ToList();
-
- }
-
- [Route("StateDetails/{counryId}")]
- [HttpGet]
- public List<State_Details> BindState(string counryId)
- {
- IEnumerable<State_Details> lstState = new List<State_Details>();
- try
- {
- using (TestDBEntities objEntity = new TestDBEntities())
- {
- lstState = objEntity.State_Details.Where(a => a.Country_Code == counryId).ToList();
- }
- }
- catch(Exception)
- {
- throw;
- }
- return lstState.ToList();
-
- }
-
- [Route("CityDetails/{cityId}")]
- [HttpGet]
- public List<District_Details> BindCity(string cityId)
- {
- IEnumerable<District_Details> lstDistrict = new List<District_Details>();
- try
- {
- using (TestDBEntities objEntity = new TestDBEntities())
- {
-
- lstDistrict = objEntity.District_Details.Where(a => a.State_Code == cityId).ToList();
- }
- }
- catch(Exception)
- {
- throw;
- }
- return lstDistrict.ToList();
- }
- }
- }
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.
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.
Setting properties of Country, State, and City
Now, write all the properties of the classes that match with the database.
country.model.ts
- export class Country {
- Country_Code :string;
- Country_Name :string;
- }
state.model.ts
- export class State {
- State_Code : string;
- State_Name : string;
- }
city.model.ts
- export class City {
- District_Code : string;
- District_Name : string;
- }
Now, open common.service.ts and first, import necessary classes and libraries and then, make calls to the Web API methods.
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { Country } from '../model/country.model';
- import { State } from '../model/state.model';
- import { City } from '../model/city.model';
-
- @Injectable({
- providedIn: 'root'
- })
- export class CommonService {
- readonly url = 'http://localhost:50707/Api/Demo/';
- listCountry : Country[];
- listState: State[];
- listCity: City[];
- constructor(private http: HttpClient) { }
-
- CountryList() {
- this.http.get(this.url + 'CountryDetails').toPromise().then(result=>this.listCountry = result as Country[])
- }
-
- StateByCountry(countryID:string) {
- return this.http.get(this.url + 'StateDetails/' + countryID).toPromise().then(result=>this.listState = result as State[])
- }
-
- DistrictByState(stateID:string) {
- return this.http.get(this.url + 'CityDetails/' + stateID).toPromise().then(result=>this.listCity = result as City[])
- }
- }
Component
Now, open country.component.ts file and write below code.
- import { Component, OnInit } from '@angular/core';
- import { CommonService } from '../shared/common.service';
- @Component({
- selector: 'app-country',
- templateUrl: './country.component.html',
- styleUrls: ['./country.component.css']
- })
- export class CountryComponent implements OnInit {
- constructor(private service:CommonService) {
- }
- ngOnInit() {
- this.service.CountryList();
- }
- BindState(countryId : string){
- this.service.StateByCountry(countryId);
- }
- BindCity(stateId : string){
- this.service.DistrictByState(stateId);
- }
- }
Design HTML
Let us design our HTML page now. Open country.component.html and write the following HTML code.
- <div class="container">
- <br>
- <h2>Cascading Dropdownlist Example in Angular 7</h2>
- <hr>
- <br>
- <div class="row">
- <div class="col-md-2">
- <label>Country Name</label>
- </div>
- <div class="col-md-6">
-
- <select name="Country" (change)="BindState($event.target.value)" class="form-control">
- <option value="undefined">Select Country Name</option>
- <option *ngFor="let country of service.listCountry" [value]="country.Country_Code">
- {{country.Country_Name}}
- </option>
- </select>
-
- </div>
- </div>
- <div class="row">
- <div class="col-md-2">
- <label>State Name</label>
- </div>
- <div class="col-md-6">
-
-
- <select name="State" class="form-control" (change)="BindCity($event.target.value)">
- <option value="undefined">Select State Name</option>
- <option *ngFor="let country of service.listState" [value]="country.State_Code">
- {{country.State_Name}}
- </option>
- </select>
- </div>
- </div>
-
- <div class="row">
- <div class="col-md-2">
- <label>State Name</label>
- </div>
- <div class="col-md-6">
- <select name="City" class="form-control">
- <option value="undefined">Select City Name</option>
- <option *ngFor="let city of service.listCity" [value]="city.District_Code">
- {{city.District_Name}}
- </option>
- </select>
- </div>
- </div>
- </div>
Now, let's add all required libraries in app.module.ts. Open the app.module.ts class and write the below code.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import{HttpClientModule} from '@angular/common/http';
- import { CountryComponent } from './country/country.component';
- import { CommonService } from './shared/common.service';
-
- @NgModule({
- declarations: [
- AppComponent,
- CountryComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- HttpClientModule
- ],
- providers: [CommonService],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Setting app.component.ts
Open app.component.html and write the below code.
- <div class="container">
- <app-country></app-country>
- </div>
Setting Index.html
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>BindDropDown</title>
- <base href="/">
-
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/x-icon" href="favicon.ico">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
- </head>
- <body>
- <app-root></app-root>
-
- </body>
- </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.
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,
- using System.Web.Http.Cors;
And write the below code inside the Register method.
- var cors = new EnableCorsAttribute("*", "*", "*");
- 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.
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.