Introduction:
In this article, we will learn ASP.NET Core web API with angular 5 data binding using with ngFor.
• Create SQL Server Database
• Create Web API with ASP.NET Core
• Install Entity Framework
• Create angular 5 Application
• Data Binding Using with ngFor
Create SQL Server Database:
Open your SQL Server, Click New Query window & Run the below SQL script, it will create new table & insert some data.
SQL Script
USE [master] GO CREATE DATABASE [DBFirst] USE [DBFirst] CREATE TABLE [dbo].[EmpMaster]( [Row_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL, [Emp_Code] [varchar](10) NULL, [Emp_FName] [varchar](50) NULL, [Emp_LName] [varchar](50) NULL, [Emp_Status] [bit] NULL, [Emp_DOB] [datetime] NULL, [Emp_Maritalstatus] [varchar](10) NULL, [Emp_Role] [varchar](50) NULL, [Emp_Department] [varchar](50) NULL, [Emp_Address] [varchar](500) NULL, [Emp_Profilestatus] [int] NULL, [Emp_Expriance] [int] NULL, [Create_By] [varchar](50) NULL, [Create_Date] [datetime] NULL, CONSTRAINT [PK_EmpMaster] PRIMARY KEY CLUSTERED ( [Row_id] 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 SET ANSI_PADDING OFF GO SET IDENTITY_INSERT [dbo].[EmpMaster] ON INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(1 AS Numeric(18, 0)), N'1000', N'Amit ', N'Sharma', 1, CAST(0x0000532D00000000 AS DateTime), N'Married', N'Admin', N'Dev', N'California', 100, 20, N'Thiru', CAST(0x0000A7BA00000000 AS DateTime)) INSERT [dbo].[EmpMaster] ([Row_id], [Emp_Code], [Emp_FName], [Emp_LName], [Emp_Status], [Emp_DOB], [Emp_Maritalstatus], [Emp_Role], [Emp_Department], [Emp_Address], [Emp_Profilestatus], [Emp_Expriance], [Create_By], [Create_Date]) VALUES (CAST(2 AS Numeric(18, 0)), N'2000', N'Erik ', N'Dietrich', 0, CAST(0x00007E0F00000000 AS DateTime), N'Married', N'Employee', N'Dev', N'Washington', 50, 10, N'Thiru', CAST(0x0000A7BA00000000 AS DateTime)) SET IDENTITY_INSERT [dbo].[EmpMaster] OFF /****** Object: StoredProcedure [dbo].[PC_EmpMaster] Script Date: 01/21/2018 20:28:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO
Create Web API with ASP.NET Core:
Open Visual Studio 2017
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core1.png)
Go to New menu >Click New & Project. Now it will open New Project Window
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core2-700x394.png)
You can select ASP.NET Core Web Application. Enter the name of project in “Solution name” textbox then click OK button.
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core3-700x456.png)
One more Window will be appearing. Select .Net Core with ASP.NET Core 2.0 Web API in this popup & Click OK button
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core4.png)
Some list will be opened in the solution Explorer
.Net Core is cross platform development framework.So we can make application for Mac,Linux & Windows Operating Systems
Install Entity Framework:
Run the below commands in NuGet Package Manger > Package Manger Console. It will be using some Entity Framework tools to create a model from the Database and ASP.NET Core Scaffolding tools to create a Controllers and Views.
Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
Now we want to create the Entity Framework model based on your created database. So that run the this command in Package Manger Console
Scaffold-DbContext "Server=MYLTOP;Database=DBFirst;User ID=sa;Password=XXX;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Once you will be done on console, Model will be created like below the screen
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core5.png)
Now Services are automatically registered with Dependency Injection on application startup. You want to remove the inline context configuration from DBFirstContext.cs
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(@"Server=MYLTOP;Database=DBFirst;UserID=sa;Password=XXX;"); } }
Add the below Constrictor line for it will allow configuration to be passed into the context Dependency Injection
public DBFirstContext(DbContextOptions<DBFirstContext> options) : base(options){ }
Then we will register this service in startup.cs. So the following Header & Services Code to be added in the existing lines
using DotNetCoreAPI.Models; using Microsoft.EntityFrameworkCore;
We want to change the Origin URL allowed to access. So that replaces the following methods in the startup.cs file. Because we can avoid “Access-Control-Allow-Origin” issue
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddCors(options => { options.AddPolicy("AllowAll", p => { p.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); var connection = @"Server=MYLTOP;Database=DBFirst;User ID=sa;Password=XXX;"; services.AddDbContext<DBFirstContext>(options => options.UseSqlServer(connection)); }
This method gets called by the run-time. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage();} app.UseCors("AllowAll"); app.UseMvc(); }
Right click on Controllers > Add New Controller > Select API Controller with actions, using Entity Framework
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core6-700x395.png)
Once Click to Add Button, One more popup will open and it will be loaded the all the Table model on model class & all Database Context will be loaded in the Data context class. If you need change the controller name
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core7-300x106.png)
Now Run the Application (Click IIS Express (Play)) & ASP.NET Core Web API has been read for any of the application. We are going to use angular application.
Create angular 5 Application
Open the Visual Studio Code. If you want to install VS Code, Click Here. Then make sure that if you installed node JS else Click Here.
Go to Terminal & Run below the line for installing Angular Cli.
npm install -g @angular/cli@latest ng new UsingCoreAPI cd path\UsingCoreAPI
It will take few minutes for setup installation.
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core9.png)
Once it will complete, we will import Angular Service Module in app.component.js & Accessing the ASP.NET Core Web API using Http get function
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Angular 5 Using ASP.NET MVC Core API'; getEmpData: any = []; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('http://localhost:54401/api/EmpMasters') .subscribe ( (data) => { this.getEmpData = data; }); }}
Change the compiler options to be false in tsconfig.json file.
"compilerOptions": { "noImplicitAny": false}
We can test your Web API over the Google ARC Tools & some data has been returned.
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core7.1-300x251.png)
This Json Data will load to the html page using angular *ngFor
<table class="table"> <thead> <tr> <td>Employee Codetd> <td> Nametd> <td>Departmenttd> <td>Locationtd> </tr> </thead> <tbody> <tr *ngFor="let emp of getEmpData"> <td>{{emp?.empCode}}</td> <td>{{emp?.empFname}} {{emp?.empLname}}</td> <td>{{emp?.empDepartment}}td> <td>{{emp?.empAddress}}td></tr></tbody>table>
Run the ng serve command in the VS Code Terminal. After executed this line open your browser on http://localhost:4200/
![](https://netkalon.com/wp-content/uploads/2018/01/ng5Core8-300x181.png)
Tips:😊
You must know about those difference:
- GET requests can be bookmarked & requests have length restrictions
- POST requests cannot be bookmarked & have no restrictions on data length
Conclusion
In this article, we have learned ASP.NET Core web API with angular 5 data binding using with ngFor. If you have any queries, please tell me through the comments sectionbecause your comments are very valuable.
Happy Coding!…
Leave a Reply