In this article, we are going to learn how to bind Dropdown List with Web API in Angular with ASP.NET Core MVC.
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.
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.
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.
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.
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.
Data in CountryMaster Table
Now, after completing with database part, next we are going to add DBcontext and set up the database connection.
Add Model (CountryMaster)
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”.
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.
Setting Connection String in appsettings.json
Here, setting up connection is new so we need to add it in JSON Format.
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.
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…
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.
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.
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.
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
- import { Injectable } from '@angular/core';
- import { Http, Response, Headers } from '@angular/http';
- import 'rxjs/add/operator/map'
- import { Observable } from 'rxjs/Observable';
-
- @Injectable()
- export class CountryDataService
- {
- private actionUrl: string;
- constructor(private _http: Http)
- {
- this.actionUrl = 'http://localhost:61384/api/CountryAPI/';
- }
-
- public GetAllCountry = (): Observable<any> =>
- {
- return this._http.get(this.actionUrl)
- .map((response: Response) => <any>response.json());
-
- }
- }
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
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
- import { Component } from '@angular/core';
- import { CountryDataService } from '../app/Services/CountryDataService';
- import { CountryMaster } from '../app/CountryMaster.Model';
-
- @Component({
- templateUrl: 'app/Demo.html',
- providers: [CountryDataService]
- })
-
- export class DemoComponent
- {
- countries: CountryMaster[];
- selectedCountry: number;
-
- constructor(private CountryService : CountryDataService)
- {
- this.CountryService.GetAllCountry().subscribe(data => this.countries = data,
- error => console.log(error),
- () => console.log('Get all complete'));
- }
-
- onSubmit() {
- console.log(this.selectedCountry);
- alert(this.selectedCountry);
- }
- }
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
Adding Demo.html template in app folder
Code snippet of demo.html template
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- </head>
- <body>
-
- <form #DropngForm="ngForm" novalidate (ngSubmit)="onSubmit()">
- <div class="row">
- <div class="col-lg-4">
- <label>Country:</label>
- <select required name="Country"
- #refCountry="ngModel"
- class="form-control" [(ngModel)]="selectedCountry">
- <option value="undefined">Please select Value</option>
- <option *ngFor="let country of countries"
- [ngValue]="country.id">
- {{country.name}}
- </option>
- </select>
- <br />
- <div *ngIf="!refCountry.valid && (refCountry.dirty || refCountry.touched)"
- class="alert alert-danger">
- <div [hidden]="!refCountry.errors.required">
- Name is required
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-lg-4">
- <label>Selected Country : {{refCountry.value}}</label>
- </div>
- </div>
- <div class="row">
- <div class="col-lg-4">
- </div>
- </div>
- <div class="row">
- <div class="col-lg-4">
- <button type="submit" class="btn btn-default"
- [disabled]="!DropngForm.form.valid">
- Submit
- </button>
- </div>
- </div>
- </form>
- </body>
- </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.
- <select required name="Country"
- #refCountry="ngModel"
- class="form-control" [(ngModel)]="selectedCountry">
- <option value="undefined">Please select Value</option>
- <option *ngFor="let country of countries"
- [ngValue]="country.id">
- {{country.name}}
- </option>
- </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
- import { Component } from '@angular/core'
- @Component({
- templateUrl : 'app/Homepage.html'
- })
- export class HomeComponent {
-
- }
After adding Home Component, next we are going to add Homepage.html to app folder.
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
- import { NgModule } from "@angular/core";
- import { BrowserModule } from "@angular/platform-browser";
- import { AppComponent } from "../app/app.component";
- import { RouterModule } from '@angular/router';
- import { DemoComponent } from '../app/Demo.Component';
- import { HomeComponent } from '../app/Home.Component';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule,
-
- RouterModule.forRoot([
- {
- path: 'Home',
- component: HomeComponent
- },
- {
- path: 'Demo',
- component: DemoComponent
- },
- { path: '', redirectTo: '/Home', pathMatch: 'full' }],
- { useHash: true }
- )],
- declarations: [AppComponent, DemoComponent, HomeComponent],
- bootstrap: [AppComponent]
- })
- 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
Finally, run your application.
Final Out