Binding Dropdown List In Angular With ASP.NET Core Web API

After selecting a project a new dialog will pop up with name “New Project” now from the left panel just select Templates inside Templates select Visual C# à The Web after that choosing it will show a list of Project Templates as shown in below dialog.

In this article, we are going to learn how to bind Dropdown List with Web API in Angular with ASP.NET Core MVC.

ASP.NET Core

Let’s start with creating a simple ASP.NET Core project.

Link to Source Code.

Starting Visual Studio

Open Visual Studio 2017 IDE for creating a project. From Menu, select File and inside that, select New >> Project.

ASP.NET Core

After selecting a project, a new dialog will pop up with name “New Project”. Now, from the left panel, just select Templates >> Visual C# >> Web. Choosing it will show a list of Project Templates, as shown in below dialog.

ASP.NET Core

In this project template, we are going to select “ASP.NET Core Web Application (.Net Framework)” and name project as “WebAngularExample1” and click OK button to create a project.

ASP.NET Core

After clicking on OK button, a new dialog will pop up for Template selection. In there, we are going to choose “Web Application” and finally click on OK button to create a project.

ASP.NET Core

Wow, we have created our first project in ASP.NET Core. Now, let’s start to setup Angular in this project.

The next step is to set up an Angular application which is given in details at the given link.

After completing with the configuration of the application, next we are going to have a look at the database.

Creating Database

I have created a database with name DemoDB and inside that I have added CountryMaster table which has a list of Countries that we are going to bind to the Dropdown list.

ASP.NET Core

Data in CountryMaster Table

ASP.NET Core

Now, after completing with database part, next we are going to add DBcontext and set up the database connection.

Add Model (CountryMaster)

ASP.NET Core

ASP.NET Core

After adding Country model, next we are going set up database connection with the application.

Setting Database Connection with Application

The first thing we are going to add is a DBcontext folder and in that folder, we are going to add a class with name “DatabaseContext”.

ASP.NET Core

After adding DatabaseContext class next we have created a constructor of this class which takes DatabaseContext as input.

And, we have also added CountryMaster DbSet.

ASP.NET Core

Setting Connection String in appsettings.json

Here, setting up connection is new so we need to add it in JSON Format.

ASP.NET Core

After setting database connection string, next we are going to set Dependency Injection.

Setting Connection Dependency Injection

In this part, we are first going to read Connection string from an appsetting.json file and next, we are going to setup dependency injection; wherever we find DatabaseContext, inject the connection there.

ASP.NET Core

Now we, have completed setting up database connection next step is to add Web API.

Creating Web API

In this part, we are going to create Web API which will return list if Country.

For adding Web API, just right click on controller folder à then choose Add à New Item…

ASP.NET Core

A new dialog will pop up with name Add New Item inside that choose ASP.NET Core panel from left panel - inside that choose - Web - ASP.NET after that in middle panel you will see all templates related to ASP.NET from that choose Web API Controller and Name it as “CountryAPIController” and click on Add button to Create.

ASP.NET Core

After Creating Web API next we are going to configure it to get data from the database.

While we are configuring it first thing we need to do is to set constructor of class for injecting dependency of DatabaseContext class.

After getting an instance of DatabaseContext class next we are going to access DbSet (Country Master) from this instance and get List of Countries and convert it into Array in Http Get Action Verb.

ASP.NET Core

Now we have completed with creating Web API next step we are going to add a Service in app folder for calling Web API and get a list of country to bind.

Creating Service in app folder

In this step, we are going to create a Service folder inside app folder.

ASP.NET Core

Inside this folder, we are going to add a Typescript file with name “CountryDataService.ts”

Inside this file we are going to create a class with name “CountryDataService.ts” and inside this class, we are going to write a method with name “GetAllCountry” in this method we are going to call Web API (“CountryAPI”) to get data.

Code snippet of CountryDataService

  1. import { Injectable } from '@angular/core';  
  2. import { Http, Response, Headers } from '@angular/http';  
  3. import 'rxjs/add/operator/map'  
  4. import { Observable } from 'rxjs/Observable';  
  5.   
  6. @Injectable()  
  7. export class CountryDataService  
  8. {  
  9.     private actionUrl: string;  
  10.     constructor(private _http: Http)  
  11.     {  
  12.         this.actionUrl = 'http://localhost:61384/api/CountryAPI/';  
  13.     }  
  14.   
  15.     public GetAllCountry = (): Observable<any> =>  
  16.     {  
  17.         return this._http.get(this.actionUrl)  
  18.             .map((response: Response) => <any>response.json());  
  19.   
  20.     }  
  21. }  

After creating Service next we are going add a Model which is also (Typescript file).

Creating (Model) CountryMaster.Model.ts in app folder

We are going to add Typescript file with name CountryMaster.Model.ts and in this file we are going to add properties

ASP.NET Core

After creating Model next we are going add a Component where we are going to call Service which we have created.

Creating Demo.Component.ts in app folder

In this part, we are going to add a Typescript file with name “Demo.Component.ts” and in this file, we are going to add DemoComponent class.

After adding “DemoComponent” class next we are going to import Model (CountryMaster.Model.ts), then we are going to import Service “CountryDataService”.

Code snippet of DemoComponent

  1. import { Component } from '@angular/core';  
  2. import { CountryDataService } from '../app/Services/CountryDataService';  
  3. import { CountryMaster } from '../app/CountryMaster.Model';  
  4.   
  5. @Component({  
  6.     templateUrl: 'app/Demo.html',  
  7.     providers: [CountryDataService]  
  8. })  
  9.   
  10. export class DemoComponent  
  11. {  
  12.     countries: CountryMaster[];  
  13.     selectedCountry: number;  
  14.   
  15.     constructor(private CountryService : CountryDataService)  
  16.     {  
  17.         this.CountryService.GetAllCountry().subscribe(data => this.countries = data,  
  18.             error => console.log(error),  
  19.             () => console.log('Get all complete'));  
  20.     }  
  21.   
  22.     onSubmit() {  
  23.         console.log(this.selectedCountry);  
  24.         alert(this.selectedCountry);  
  25.     }  
  26. }  

After importing service next we are going set templateUrl (Demo.html) which we are going to create next, but meanwhile we can set providers (services) here we are going to use service “CountryDataService”, after setting providers Next we need to get data from service on load of this file right, for doing that we are going to call “CountryDataService” in constructor of class as shown above.

After getting values from service next we are going to assign these values to countries variable (countries: CountryMaster[]) and this variable will be used on a template for binding data.

After adding Demo.Component.ts file next we are going to Demo.html template.

Adding Demo.html template

ASP.NET Core

Adding Demo.html template in app folder

Code snippet of demo.html template

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.   
  9.     <form #DropngForm="ngForm" novalidate (ngSubmit)="onSubmit()">  
  10.         <div class="row">  
  11.             <div class="col-lg-4">  
  12.                 <label>Country:</label>  
  13.                 <select required name="Country"  
  14.                         #refCountry="ngModel"  
  15.                         class="form-control" [(ngModel)]="selectedCountry">  
  16.                     <option value="undefined">Please select Value</option>  
  17.                     <option *ngFor="let country of countries"  
  18.                             [ngValue]="country.id">  
  19.                         {{country.name}}  
  20.                     </option>  
  21.                 </select>  
  22.                 <br />  
  23.                 <div *ngIf="!refCountry.valid  && (refCountry.dirty || refCountry.touched)"  
  24.                      class="alert alert-danger">  
  25.                     <div [hidden]="!refCountry.errors.required">  
  26.                         Name is required  
  27.                     </div>  
  28.                 </div>  
  29.             </div>  
  30.         </div>  
  31.         <div class="row">  
  32.             <div class="col-lg-4">  
  33.                 <label>Selected Country : {{refCountry.value}}</label>  
  34.             </div>  
  35.         </div>  
  36.         <div class="row">  
  37.             <div class="col-lg-4">  
  38.             </div>  
  39.         </div>  
  40.         <div class="row">  
  41.             <div class="col-lg-4">  
  42.                 <button type="submit" class="btn btn-default"  
  43.                         [disabled]="!DropngForm.form.valid">  
  44.                     Submit  
  45.                 </button>  
  46.             </div>  
  47.         </div>  
  48.     </form>  
  49. </body>  
  50. </html>  

After adding Demo.html file we are going to copy paste the above code snippet in Demo.html template.

Let’s understand how to bind dropdown list in angular.

We have got arrays of countries which we are going to use for binding drop-down list for doing this we have taken select html tag and for bind data we need to iterate Countries array such that we can bind to each option an unique value for iterating we are going use “ngFor” which is a built-in Directive that allows us to iterate over a collection, and to assign value we are going use [ngValue] directive and to display text we are going use double braces.

  1. <select required name="Country"  
  2.         #refCountry="ngModel"  
  3.         class="form-control" [(ngModel)]="selectedCountry">  
  4.     <option value="undefined">Please select Value</option>  
  5.     <option *ngFor="let country of countries"  
  6.             [ngValue]="country.id">  
  7.         {{country.name}}  
  8.     </option>  
  9. </select>  

After understanding bind dropdown list in Angular, next we are simply going to add another component “Home.Component.ts”

Adding Home.Component.ts Component

This will be main page which will be displayed when application loads.

In this part, we are going to add a Typescript file with name “Home.Component.ts” and in this file, we are going to add Home Component class.

Code snippet of HomeComponent

  1. import { Component } from '@angular/core'  
  2. @Component({  
  3.     templateUrl : 'app/Homepage.html'  
  4. })  
  5. export class HomeComponent {  
  6.   
  7. }  

After adding Home Component, next we are going to add Homepage.html to app folder.

ASP.NET Core

After adding Home.Component.ts and Homepage.html, we need to configure routing and add new routing in “Demo.Component.ts” file.

Configuring Routing in app.module.ts file

We write all routing in app.module.ts Typescript file where we import RouteModule and we declare Routing path and in component (we declare component for that path).

Code snippet of app.module.ts

  1. import { NgModule } from "@angular/core";  
  2. import { BrowserModule } from "@angular/platform-browser";  
  3. import { AppComponent } from "../app/app.component";  
  4. import { RouterModule } from '@angular/router';  
  5. import { DemoComponent } from '../app/Demo.Component';  
  6. import { HomeComponent } from '../app/Home.Component';  
  7. import { FormsModule } from '@angular/forms';  
  8. import { HttpModule } from '@angular/http';  
  9. @NgModule({  
  10.     imports: [BrowserModule, FormsModule, HttpModule,  
  11.   
  12.         RouterModule.forRoot([  
  13.             {  
  14.                 path: 'Home',  
  15.                 component: HomeComponent  
  16.             },  
  17.             {  
  18.                 path: 'Demo',  
  19.                 component: DemoComponent  
  20.             },           
  21.             { path: '', redirectTo: '/Home', pathMatch: 'full' }],  
  22.             { useHash: true }  
  23.             )],  
  24.     declarations: [AppComponent, DemoComponent, HomeComponent],  
  25.     bootstrap: [AppComponent]  
  26. })  
  27. export class AppModule { }  

Now, we have completed entire configuration. Let’s save application.

Finally, your application should look like the one shown in the below snapshot.

Solution Explorer view after configuration of project

ASP.NET Core

Finally, run your application.

Final Out

ASP.NET Core