find and solve || findandsolve.com
Please wait.....

Insert update delete using angular with asp.net core crud example

Insert update delete using angular with asp.net core crud example

CRUD Example In asp.net core with angular 8

We are going to create an new  web application using ASP.NET Core 2.2 and Angular  with Entity Framework Core Code  first approach.We will be creating a sample Staff Record Management system
 

 Prerequisites

⦁ Install .NET Core 2.2 or above SDK from https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro#windowscmd'
⦁ Install the latest version of Visual Studio 2017 or 2019 from https://visualstudio.microsoft.com/downloads/
⦁ Download and install the latest version of Node.js from https://nodejs.org/en/download/
⦁ SQL Server 2014/2016/2017  or above from https://www.microsoft.com/en-us/sql-server/sql-server-editions-express 

 (Or you can download antoher sites free edition)
⦁ Angular CLI from https://cli.angular.io/

 

 Installed Node.js and you can open the Node.js command prompt.And then command in the command prompt to install the

 Angular 8 CLI.First you make sure above are installed or not.

You can get the source code from GIthub.This repository has been updated to Angular 8 and ASP.NET Core 2.2.


Create MVC Web Application

Open Visual Studio 2017 and select File > New > Project.After selecting the project, a new project dialog will open in your computer given below image.Select .NET Core  Web  Application inside Visual C# menu from the left panel given.Then,select ASP.NET Core Web Application from available project types list and then Put the name of the project as "FirstApp" and press OK.

Create MVC Web Application

After clicking on OK button,a new dialog will open asking you to select the project template.There are two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.2” from these dropdowns and select “Angular” template and press OK Button.

 

Add angular template in asp.net core

Now, our project will be created. You can see the folder structure in Solution Explorer as shown in the given below image.
the folder structure in Solution Explorer

The ClientApp folder where the client side of our application resides. Inside the ClientApp/app/components folder.There is already have few components created which are provided by default with the Angular template in VS 2017.These components won’t affect our project,but we will delete fetchdata and counter folders from our application folder path ClientApp/app/components folder.
 

Adding the Model to the Application

We are using Entity Framework core Code first approach to create our models.First create New Folder under project solution. Right click on your project solution  and select Add > New Folder.Name your folder  Entities 
Adding the Model to the Application

 Right click on Entities folder and select Add > Class. Name your Connection Class  DbContext.cs and click Add button.

 And also add your entity model  as same folder[Entity model is represent sql Table].

 At this point of time, the Entities folder will have the following structure.
 

Entities folder will have the following structure.Open DBContext.cs and put the following code to handle Connection operations. 

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace FirstApp.Entities
{
    public class DBContext : DbContext
    {
        private IConfigurationRoot _config;
        public DBContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }
        public DbSet<Staff> Staffs { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);
             //connection string get by appsetting.json
        }
    }
}

 After that also Open Staff.cs and put the following code. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp.Entities {     public class Staff     {         public string Id { get; set; }         public string FullName { get; set; }         public string Address { get; set; }         public string Gender { get; set; }     } }


  Open appsettings.json and put the following code to handle Connection string.

 appsettings.json handle connection string in asp.net core.put the code in this appsettings.jsong 

 to connect client to database server.like that. 


   {
  "ConnectionStrings": {
    "windowsAuthentication": true,
    "DefaultConnection": "Data Source=DESKTOP-9KQH8Q0;Database=FirstApp;Trusted_Connection=True;", //this is windows athenticaiton
    //"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=FirstApp;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
    //"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=FirstApp;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
    //"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=FirstApp;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
    //"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=FirstApp;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
}


 

Open Startup.cs and put the following code  

using FirstApp.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FirstApp {     public class Startup     {         private IConfigurationRoot _config;         public Startup(IHostingEnvironment env)         {             var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)                         .AddJsonFile("appsettings.json");             _config = ConfigBuilder.Build();         }
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.         public void ConfigureServices(IServiceCollection services)         {             services.AddSingleton(_config);             services.AddDbContext<DBContext>();             services.AddMvc();             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            // In production, the Angular files will be served from this directory             services.AddSpaStaticFiles(configuration =>             {                 configuration.RootPath = "ClientApp/dist";             });         }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)         {             if (env.IsDevelopment())             {                 app.UseDeveloperExceptionPage();             }             else             {                 app.UseExceptionHandler("/Error");                 // The default HSTS value is 30 days. You may want to change this for production scenarios
                //see https://aka.ms/aspnetcore-hsts.                 app.UseHsts();             }
            app.UseHttpsRedirection();             app.UseStaticFiles();             app.UseSpaStaticFiles();
            app.UseMvc(routes =>             {
                    routes.MapRoute(                     name: "default",                     template: "{controller}/{action=Index}/{id?}");             });
            app.UseSpa(spa =>             {                 // To learn more about options for serving an Angular SPA from ASP.NET Core,                 // see https://go.microsoft.com/fwlink/?linkid=864501
                spa.Options.SourcePath = "ClientApp";
                if (env.IsDevelopment())                 {                     spa.UseAngularCliServer(npmScript: "start");                 }             });         }     } }

 

After that we are ready to Migration our project.EF Core migrations are a set of commands which you can execute in NuGet Package Manager Console or in dotnet Command Line Interface (CLI).
More Details :https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli

This is code first application so we are ready to migration our First project.


Select View > other Windows >Package Manager Console given below.

Package Manager Console

After click Package Manager Console,At this point of time, the Package Manager Console  will have the following structure.And Type "Add-Migration FirstMigration" as given below position.And Enter.

Add-Migration After Add-Migration FirstMigration,Show the result on Package Manager Console given below.After Migration is success then you must update your database  Update-Database like given below and then Enter.
Add-Migration  layout

See your sql databse,there is create databse "FirstApp" and also create table "Staff".

 

Adding the Web API Controller to the Application 

Right click on Controllers folder and select Add >> New Item.
An “Add New Item” dialog box will open. Select ASP.NET from the left panel, then select “Web API Controller Class” from templates panel and put the name as StaffController.cs. Press OK.
Adding the Web API Controller to the Application

 


Open StaffController.cs file and put the following code into it. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FirstApp.Entities;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace FirstApp.Controllers {     [Route("api/[controller]")]     public class StaffController : Controller     {         private readonly DBContext _connection;         public StaffController(DBContext connection)         {             _connection = connection;         }         [HttpGet]         [Route("GetStaffList")]         public IActionResult GetStaffList()         {             var data = _connection.Staffs.ToList();             return Ok(data);         }     } }


 Check result is fine or not in asp.net core 2.2.So I have Inserted record manually in sql server. given below
 Open sql server select database FirstApp and run script on this database

         

NSERT INTO Staffs (Id,FullName,Address,Gender) VALUES('1','Devin','Liotyo','Male')--insert statement in sql server

 After Run this sql script on FirstApp Databse then run your Asp.Net core project FirstApp.Output is given below.Api Response data display

We are done with our backend logic and asp.net core structure. So, we will now proceed to code our frontend using Angular.


 Create the Angular Service

We will create an Angular service which will Web api response to Json formate and pass into components.Right click on your  ClientApp > src > app  folder and then Add > New Folder and name the folder as components.Then again Right click on your  ClientApp > src > app  folder and then Add > New Folder and name the folder as staff-service.


Right click on staff-service folder and select Add >> New Item. An "Add New Item" dialog box will open.

Select Scripts from the left panel, then select "TypeScript File" from templates panel, and put the name as staff.service.ts. Press OK 

Open staff-service.ts file and put the following code into it.

Create the Angular Service

import { Injectable, Inject } from '@angular/core';
import { Http, Response, } from '@angular/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable()
export class StaffService {
  appUrl: string;   constructor(private _http: Http, private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {     this.appUrl = baseUrl;
  }
  getStaffList() {     return this.http.get<any>(this.appUrl + "api/Staff/GetStaffList")       .pipe(map(data => {         return data;       }));   }
  saveStaff(staffInfoForm) {     return this.http.post<any>(this.appUrl + "api/CompanyInfo/SerchCompany", staffInfoForm)       .pipe(map(data => {         return data;       }));   }   editStaff(staffId: string) {    return this.http.get<any>(this.appUrl + "api/CompanyInfo/GetCompanyInfoByCompanyId/" + staffId)       .pipe(map(data => {         return data;       }));   }   delete(staffId: string) {     return this._http.get(this.appUrl + "api/CompanyInfo/Delete/" + staffId)       .pipe(map(data => {         return data;       }));   }
  errorHandler(error: Response) {     console.log(error);     return Observable.throw(error);   } }

Creating Angular Components

We will be adding two components to our Angular given below.

a.staff-list-component    – to display all the Staff data and delete an existing Staff data.
b.staff-add-component   – to add a new Staff data or edit an existing Staff data.

Right click on ClientApp/app/components folder and select Add > New Folder and name the folder as staff-list.


Right click on staff-list folder and select Add > New Item. An "Add New Item" dialog box will open.Select Scripts from the left panel, then select "TypeScript File" from templates panel, and put the name as staff-list-component.ts. Press OK. This will add a TypesSript file inside staff-list folder.You can see layout after add a TypeScript file inside staff-list given below.
 

Aps.Net core with TypeScript File

Right click on staff-list folder and select Add > New Item. An "Add New Item" dialog box will open. 
Select Web > Content  from the left panel, then select "HTML Page" 

from templates panel,and put the name as staff-list-component.html then Press OK.

This will add a HTML file inside staff-list folder.
  

Similarly create a add-staff folder inside ClientApp/app/components folder and add staff-add-component.ts typescript and staff-add-component.html HTML file to it.

Now our ClientApp/app/components will look like given below:



Open staff-list-component.ts file and put the following code to it:
import { Component, Inject from '@angular/core';
import { StaffService from '../../staff-service/staff.service';
@Component({
  selector: 'app-fetch-data',
  templateUrl: './staff-list-component.html'
})
export class GetStaffList {
  public staffList: StaffModeModel[];
  constructor(private _staffService: StaffService) {
    this.getStaffList();
  }
  getStaffList() {
    this._staffService.getStaffList().subscribe(
      data => this.staffList = data
    )
  }
  delete(staffId) {
      var isDelete = confirm("Do you want to delete Staff with Id: " + staffId);
    if (isDelete) {
      this._staffService.delete(staffId).subscribe((data) => {
        this.getStaffList();
      }, error => console.error(error))
    }
  }
}
interface StaffModeModel {
  id: string;
  fullName: string;
  address: string;
  gender: string;
}
Let’s understand this code. At the very top we have imported Angular modules and StaffService references. 
After this we have @Component decorator to define the template URL for this component.

Inside the GetStaffList class we have declared an array variable staffList of type StaffModeModel where StaffModeModel is an interface having the properties
same as our Stafff class. Inside the getStaffList method we are calling the getStaffList method of our service StaffService
which will return an array of Staff to be stored in staffList variable.
The getStaffList method is called inside the constructor so that the staff List will be displayed as the page loads.
Next, we have delete method which accepts staffId as parameter.
This will prompt the user with a confirmation box and if the user selects yes then it will delete the staff reocrd with this staffId.

Open staff-list-component.html file and put the following code into it.
<h1>Staff List</h1>
<p *ngIf="!staffList"><em>Loading...</em></p>
<p>
  <a [routerLink]="['/add-staff']">Create New</a>
</p>
<table class='table' *ngIf="staffList">
  <thead>
    <tr>
      <th>Staff Id</th>
      <th>Full Name</th>
      <th>Address</th>
      <th>Gender</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let s of staffList">
      <td>{{ s.id }}</td>
      <td>{{ s.fullName }}</td>
      <td>{{ s.address }}</td>
      <td>{{ s.gender}}</td>
      <td>
      <td>
        <a [routerLink]="['/staff/edit/', s.id]">Edit</a> |
        <a [routerLink]="" (click)="delete(s.id)">Delete</a>
      </td>
    </tr>
  </tbody>
</table>
We are finished with our staff-list-component.
Now open staff-add-component.ts file and put the following code into it:

import { Component, OnInit from '@angular/core';
import { Http, Headersfrom '@angular/http';
import { NgForm, FormBuilder, FormGroup, Validators, FormControlfrom '@angular/forms';
import { Router, ActivatedRoute from '@angular/router';
import { StaffService from '../../staff-service/staff.service';
import { GetStaffList from '../staff-list/staff-list-component';
@Component({
  templateUrl: './staff-add-component.html'
})
export class StaffAdd implements OnInit {
  staffForm: FormGroup;
  title: string= "Create";
  id: string;
  fullName: string;
  address: string;
  gender: string;
  errorMessage: any;
  constructor(private _fb: FormBuilder, private _avRoute: ActivatedRoute,
    private _staffService: StaffService, private _router: Router) {
    if (this._avRoute.snapshot.params["id"]) {
      this.id = this._avRoute.snapshot.params["id"];
    }
    this.staffForm = this._fb.group({
      id: '',
      fullName: '',
      address: '',
      gender: '',
    })
  }
  ngOnInit() {
    if (this.id != null) {
      this.title = "Edit";
      this._staffService.editStaff(this.id)
        .subscribe(resp => this.staffForm.setValue(resp)
          , error => this.errorMessage = error);
    }
  }
  save() {
    if (!this.staffForm.valid) {
      return;
    }
    if (this.title == "Create") {
      this._staffService.saveStaff(this.staffForm.value)
        .subscribe((data) => {
          this._router.navigate(['/staff-list']);
        }, error => this.errorMessage = error)
    }
    else if (this.title == "Edit") {
      this._staffService.updateStaff(this.staffForm.value)
        .subscribe((data) => {
          this._router.navigate(['/fetch-employee']);
        }, error => this.errorMessage = error)
    }
  }
  cancel() {
    this._router.navigate(['/staff-list']);
  }
}

This staff-add component will be used for adding and editing the staff data.Add and Edit staff data 

we have imported classes from @angular/forms. The code to create the form has been put inside the StaffAdd constructor

so that the form will be displayed as the page loads. Component will handle  Add and Edit request.

Inside ngOnInit ,We will check if the id is set then we will change the title to "Edit"
get the data for that id from our service and populate the fields in our form.

Open staff-add-component.html file and put the following given code into it.
<h1>Staff List</h1>
<p *ngIf="!staffList"><em>Loading...</em></p>
<p>
  <a [routerLink]="['/add-staff']">Create New</a>
</p>
<table class='table' *ngIf="staffList">
  <thead>
    <tr>
      <th>Staff Id</th>
      <th>Full Name</th>
      <th>Address</th>
      <th>Gender</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let s of staffList">
      <td>{{ s.id }}</td>
      <td>{{ s.fullName }}</td>
      <td>{{ s.address }}</td>
      <td>{{ s.gender }}</td>
      <td>
      <td>
        <a [routerLink]="['/staff/edit/',s.id]">Edit</a>||
        <a [routerLink]="" (click)="delete(s.id)">Delete</a>
      </td>
    </tr>
  </tbody>
</table>

Defining route and navigation menu for our Application 

Open  ClientApp > src > app >  app.module.ts file and put the following code into it.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { HttpModule } from '@angular/http';
import { StaffService } from './staff-service/staff.service';
import { GetStaffList } from './components/staff-list/staff-list-component';
import { StaffAdd } from './components/staff-add/staff-add-component';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    GetStaffList,
    StaffAdd,
    FetchDataComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'staff-list', component: GetStaffList },
      { path: 'add-staff', component: StaffAdd },
      { path: 'staff/edit/:id', component: StaffAdd },
    ])
  ],
  providers: [StaffService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here we have also imported all our components and defined the route for our application as below.

a.home – which will redirect to home component
b.staff-list – to display all staff data using staff-list-component
c.add-staff – to add new staff record using add-staff- component
d.staff/edit/:id – to edit existing staff record using staff-add-component

One last thing is to define navigation menu for our application. Open ClientApp > src > app >  nav-menu > nav-menu.component.html
 file and put the following code to it.

<header>
  <nav class='navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3'>
    <div class="container">
      <a class="navbar-brand" [routerLink]='["/"]'>FirstApp</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-label="Toggle navigation"
        [attr.aria-expanded]="isExpanded" (click)="toggle()">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse" [ngClass]='{"show": isExpanded}'>
        <ul class="navbar-nav flex-grow">
          <li class="nav-item" [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'>
            <a class="nav-link text-dark" [routerLink]='["/"]'>Home</a>
          </li>
          <li class="nav-item" [routerLinkActive]='["link-active"]'>
            <a class="nav-link text-dark" [routerLink]='["/counter"]'>Counter</a>
          </li>
          <li class="nav-item" [routerLinkActive]='["link-active"]'>
            <a class="nav-link text-dark" [routerLink]='["/staff-list"]'>Staff List</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</header>

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response