angular crud operation using mvc core web api

 

             Integrating angular with mvc core web api

 

Crete application : Open Visual Studio and select File >> New >> Project.

After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel.

Then, select “ASP.NET Core Web Application” from available project types. , AND CLICK ON NEXT

 


 

Put the name of the project as  and CLICK ON CREATE.



THEN SELECT ANGULAR

 

 


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

 


 

Here,  Controllers folders will contain our Web API controller. The point of interest for us is the ClientApp folder where the client side of our application resides. Inside the ClientApp/app/components folder, we already have few components created which are provided by default with the Angular 8 template in VS 2019.     We can see at from ClientApp/app/components folder.

Create data base and table in sqlserver

Here I created



Table design:

 


Adding the Model to the Application

We are using Entity Framework core database first approach to create our models. Navigate to Tools >> NuGet Package Manager >> Package Manager Console.

We have to install the package for the database provider that we are targeting which is SQL Server in this case. Hence run the following command:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Since we are using Entity Framework Tools to create a model from the existing database, we will install the tools package as well. Hence run the following command:

Install-Package Microsoft.EntityFrameworkCore.Tools

After you have installed both the packages, we will scaffold our model from the database tables using the following command:

 

Scaffold-DbContext "Data Source=DESKTOP-L3Q3AHO\SQLEXPRESS01;Initial Catalog=accerdb;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

 

we have successfully created our Models using EF core database first approach.

Now,the Models folder will have the following structure.

 


MODELS:




Here I have created one more model:

For binding data of type string when post data

 

 


 appsettings.json:  ADD connection string to acccess data base






then add  this connection string in startup.cs


Startup.cs





Now, we will proceed to create our Web API Controller.

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 CustomerController.cs. Press OK.

 

This will create our Web API CustomerController.cs. class. We will put all our business logic in this controller. We will call the methods  from the  Angular frontend.

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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using WebApplication2.Models;

 

namespace WebApplication2.Controllers

{

    [Route("api/customers")]

    [ApiController]

    public class customersController : ControllerBase

    {

        private readonly accerdbContext _context;

 

        public customersController(accerdbContext context)

        {

            _context = context;

        }

 

       //Get customer list

        [HttpGet]

        [Route("Getdata")]

        public async Task<ActionResult<IEnumerable<Tblcustomer>>> GetTblcustomer()

        {

            return await _context.Tblcustomer.ToListAsync();

        }

        //Get customer list BY ID

 

        [HttpGet]

        [Route("Getdata/{id}")]

        public async Task<ActionResult<Tblcustomer>> GetTblcustomer(string id)

        {

            var tblcustomer = await _context.Tblcustomer.FindAsync(id);

 

            if (tblcustomer == null)

            {

                return NotFound();

            }

 

            return tblcustomer;

        }

 

        // PUT: UPDATE CUSTOMER

        [HttpPut]

        [Route("Update")]

        public async Task<IActionResult> PutTblcustomer(Tblcustomer tblcustomer)

        {

        

 

            _context.Entry(tblcustomer).State = EntityState.Modified;

 

            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateConcurrencyException)

            {

                 throw;    

            }

 

            return NoContent();

        }

 

        //INSERT NEW CUSTOMER INTO TABLE

        [HttpPost]

        [Route("Postdata")]

        public async Task<ActionResult<Tblcustomer>> PostTblcustomer([FromBody]  Customermodel custobj )//

        {

            Tblcustomer tblcustomer = new Tblcustomer();

            tblcustomer.CustomerName = custobj.CustomerName;

            tblcustomer.CustomerCode = custobj.CustomerCode;

            tblcustomer.CustomerAmount = Convert.ToDecimal(custobj.CustomerAmount);

                _context.Tblcustomer.Add(tblcustomer);

            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateException)

            {

                if (TblcustomerExists(tblcustomer.CustomerCode))

                {

                    return Conflict();

                }

                else

                {

                    throw;

                }

            }

 

            return CreatedAtAction("GetTblcustomer", new { id = tblcustomer.CustomerCode }, tblcustomer);

        }

 

        // DELETE CUSTOMER

        [HttpDelete]

        [Route("Delete/{id}")]

        public async Task<ActionResult<Tblcustomer>> DeleteTblcustomer(string id)

        {

            var tblcustomer = await _context.Tblcustomer.FindAsync(id);

            if (tblcustomer == null)

            {

                return NotFound();

            }

 

            _context.Tblcustomer.Remove(tblcustomer);

            await _context.SaveChangesAsync();

 

            return tblcustomer;

        }

 

        private bool TblcustomerExists(string id)

        {

            return _context.Tblcustomer.Any(e => e.CustomerCode == id);

        }

    }

}


We are done with our backend logic. So, we will now proceed to code our frontend using Angular





Create the Angular Service

We will create an Angular service which will convert the Web API response to JSON and pass it to our component. 

Right click on ClientApp/app folder and then select Add >> New Item. and put the name as Customerservice.service.ts. Press OK

 

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

 

import { Injectable } from '@angular/core';

import { Customer } from './model';

 

import { HttpClient } from '@angular/common/http';

 

@Injectable({

  providedIn: 'root'

})

export class CustomerService {

 

  ApiUrl='https://localhost:44367/';    

  constructor(private httpclientHttpClient) { }    

          //GET  TABLE DATA 

  GetCustomerlist(){    

    return this.httpclient.get<Customer[]>(this.ApiUrl+'api/customers/getdata');    

    } 

    //GET DATA BY Id TO  edit

    GetCustomerById(id:string) {  

      debugger

      return this.httpclient.get(this.ApiUrl +"api/customers/getdata/" + id)  

  }  

      //delete DATA BY Id 

  deleteById(id:string) {  

    debugger

    return this.httpclient.delete(this.ApiUrl +"api/customers/Delete/" + id)  

}  

    //add new customer

  AddCustomer(Customer) {  

      debugger

      return this.httpclient.post(this.ApiUrl +'api/customers/Postdata',Customer);     

  } 

  //update customer

  UpdateCustomer(Customer) {  

    debugger

    return this.httpclient.put(this.ApiUrl +'api/customers/Update',Customer);     

}

 

 

 

 

Now, we will proceed to create our components.

Creating Angular Components

 

Now open app.component.ts file and put the following code into it:

import { Component } from '@angular/core';

import { FormBuilderValidatorsFormGroup } from '@angular/forms';

import { Customer } from './model';

import { CustomerService } from './customer.service';

 

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html'

})

export class AppComponent {

 

Customermodel :Customer = new Customer();//object

 CustomerModels :Array<Customer> = new Array<Customer>();//list object

FromCustomerFormGroup

isValidFormSubmittedboolean;

unamePattern = "^[A-Z]{3,3}[0-9]{4,4}$";//pattern

  errorMessageany;

  customerCodeforupdateany;

 

constructorprivate formbuliderFormBuilder,private customerService:CustomerService) {}

ngOnInit(): void {  

   this.FromCustomer = this.formbulider.group({  

    CustomerCode: ['', [Validators.required,Validators.pattern(this.unamePattern)]],  

    CustomerName: ['', [Validators.required]],  

    CustomerAmount: ['', [Validators.required]],  

});   

this.Loadcustomerlist();  

}  

 


//TO get all table data 

Loadcustomerlist(){   

  this.customerService.GetCustomerlist().

  subscribe(res=>this.SuccessGet(res));

}

SuccessGet(res) {

  this.CustomerModels = res;

}



//submit to add new customer

SaveCustomer(Customer) {

   this.isValidFormSubmitted = false;

   if (this.FromCustomer.invalid) {

     return;

   }

 

  if(this.customerCodeforupdate == null || undefined )

  { //ADD CUSTOMER

    this.customerService.AddCustomer(Customer).subscribe(  

      () => {  

          this.FromCustomer.reset(); 

          this.isValidFormSubmitted = true;

          this.Loadcustomerlist();

      });

  }

  else

  {

// UPDATE CUSTOMER Datails

    this.customerService.UpdateCustomer(Customer).subscribe(  

      () => {  

          this.FromCustomer.reset(); 

          this.isValidFormSubmitted = true;

          this.Loadcustomerlist();

          this.customerCodeforupdate = null;

      });

  }

}

 

//EDIT CUSTOMER

EditCustomer(code){

  debugger

  this.customerService.GetCustomerById(code). 

  subscribe(res=>this.SuccessGetbyid(res));  

}


SuccessGetbyid(res) {

  this.customerCodeforupdate =res.customerCode;

  debugger

  this.FromCustomer.controls['CustomerCode'].setValue(res.customerCode);  

  this.FromCustomer.controls['CustomerName'].setValue(res.customerName);  

   this.FromCustomer.controls['CustomerAmount'].setValue(res.customerAmount); 

}

 

//DELETE CUSTOMER

DeleteCustomer(code){

  debugger

  this.customerService.deleteById(code

  .subscribe(  

    () => {  

        this.Loadcustomerlist();

    });

}

//validations

get CustomerCode() { return this.FromCustomer.get('CustomerCode'); }

 

get CustomerName() { return this.FromCustomer.get('CustomerName'); }

 

get CustomerAmount() { return this.FromCustomer.get('CustomerAmount'); }

 

}

 

This component will be used for both adding and editing the customer data. Since we are using a form model along with client-side validation to Add and Edit customer data we have imported classes from @angular/forms. The code to create the form has been put inside the constructor so that the form will be displayed as the page loads.

Model: customer

.


The save method will be called on clicking on “Save” button of our form. Based on whether it is an Add operation or an Edit operation it will call the corresponding method from our service and then upon success redirect back to fetch-employee component.

In the last one we have also defined getter functions for the control names of our form to enable client-side validation.

Open app.component.html file and put the following code into it.

<h1>Customer Application</h1>

<form [formGroup]="FromCustomer" (ngSubmit)="SaveCustomer(FromCustomer.value)">  

Customer Code :<input  formControlName="CustomerCode" type="text" /> <br>

<div *ngIf="(CustomerCode.touched && CustomerCode.errors) || CustomerCode.errors && isValidFormSubmitted != null 

                                                                      && !isValidFormSubmitted" class ="error">

 <div *ngIf="CustomerCode.errors.required">

   CustomerCode is required

 </div>

 <div *ngIf="CustomerCode.errors.pattern">

   CustomerCode not valid.

 </div> 

</div>

Customer Name :<input    formControlName="CustomerName"  type="text"/> <br>

<div *ngIf="(CustomerName.touched && CustomerName.errors) || CustomerName.errors?.required 

                                                 && isValidFormSubmitted != null && !isValidFormSubmitted" class = "error">

   CustomerName required.

</div>

Customer Amount :<input   formControlName="CustomerAmount"  type="text"/> <br> <br>

<div *ngIf="(CustomerAmount.touched && CustomerAmount.errors )||  CustomerAmount.errors?.required 

                                                            && isValidFormSubmitted != null && !isValidFormSubmitted" class ="error">

CustomerAmount is required

</div>

<button type="submit" class="btn btn-primary" >Add Student</button>  </form>  

<table>

 <tr>

   <th>CustomerCode</th>   <th>CustomerName</th>  <th>CustomerAmount</th>

 </tr>

 <tr *ngFor="let cust of CustomerModels">

   <td>{{cust.customerCode}}</td>

   <td>{{cust.customerName}}</td>

   <td>{{cust.customerAmount}}</td> 

   <td>

    <button type="button" class="btn btn-info" (click)="EditCustomer(cust.customerCode)">Edit</button>  

    <button type="button" class="btn btn-info" (click)="DeleteCustomer(cust.customerCode)">Delete</button>  

  </td> 

</table>


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

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { FormsModuleReactiveFormsModule } from '@angular/forms';

import { HttpClientModuleHTTP_INTERCEPTORS } from '@angular/common/http';

 

import { AppComponent } from './app.component';

import { CustomerService } from './customer.service';

 

@NgModule({

  declarations: [

    AppComponent,

    

  ],

  imports: [

    BrowserModule,

    HttpClientModule,

    FormsModule,

    ReactiveFormsModule,//we used reactive forms in this application

    

  ],

  //add service to providing connection to api

  providers: [CustomerService],

  bootstrap: [AppComponent]// to start project

})

export class AppModule { }

 

 

when run the application:

output:




https://www.devglan.com/angular/angular-8-crud-example


 

Comments