CRUD SPA ASP.NET Web API and Angular
ASP-MVC-WEB-API

CRUD SPA ASP.NET Web API and Angular

Today I am going to build an ASP SPA Database First. Here we go, I will be using ASP.NET Web API in the backend and Angular in the frontend and Visual Studio 2019.

In SSMS, create a DB

CREATE DATABASE simple_crud
GO

Then create your table

CREATE TABLE [dbo].[employees](
	[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeName] [varchar](100) NULL,
	[StaffNumber] [varchar](100) NULL,
	[Email] [varchar](255) NULL,
 CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED 
(
	[EmployeeID] 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

In Visual Studio

Model

Add model

Right click model folder >>> New Item >>> Data >>> Select ADO.NET Entity Data Model

ADO.NET Entity

Then select Entity Data Model

Choose your data connection

Choose your DB objects

Then Rebuild your solution

Model validation

Replace the code in employee.cs, in your models table with the below code

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace emp_be.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class employee
    {
        [Key]
        public int EmployeeID { get; set; }

        [Required(ErrorMessage = "Enter Employee Name")]
        [StringLength(100, ErrorMessage = "Only 100 character are allowed")]
        public string EmployeeName { get; set; }

        [Required(ErrorMessage = "Enter Employee Number")]
        [StringLength(100, ErrorMessage = "Only 100 character are allowed")]
        public string StaffNumber { get; set; }

        [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}",ErrorMessage = "Please enter Valid Email ID")]
        [Required(ErrorMessage = "Please enter Student EmailID")]
        public string Email { get; set; }
    }
}

Add controller

Right click Controller >>> Add >>> Controller

Add controller

Select Web API 2 Controller with actions using Entity framework click Add

Then select your model Class and data context class.

Your Controller class will be generated in the controllers folder

//------------------------------------------------------------------------------
// <inheritdoc>
//     Employee api for getting/finding/adding/deleting employee.
//
//     Ernest Muroiwa
// </inheritdoc>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using emp_be.Models;

namespace emp_be.Controllers
{
    public class employeesController : ApiController
    {
        private DBmodel db = new DBmodel();

        /// <summary>
        /// Get all employees.
        /// </summary>
        /// <returns>Ok with all employees.</returns>
        // GET: api/employees
        public IQueryable<employee> Getemployees()
        {
            return db.employees;
        }


        /// <summary>
        /// Update existing employee.
        /// </summary>
        /// <param name="id">Id of employee.</param>
        /// <param name="patch">JSON patch operations in body.</param>
        /// <returns>Ok with updated employee.</returns>
        // PUT: api/employees/5

        [ResponseType(typeof(void))]
        public IHttpActionResult Putemployee(int id, employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != employee.EmployeeID)
            {
                return BadRequest();
            }

            db.Entry(employee).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!employeeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        /// <summary>
        /// Add a employee.
        /// </summary>
        /// <param name="employee"></param>
        /// <returns>Created status for successful post.</returns>
        // POST: api/employees

        [ResponseType(typeof(employee))]
        public IHttpActionResult Postemployee(employee employee)
        {

            db.employees.Add(employee);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
        }

        /// <summary>
        /// Deletes employee for given id.
        /// </summary>
        /// <param name="id">employee id.</param>
        /// <returns>No content status for successful deletion.</returns>
        // DELETE: api/employees/5

        [ResponseType(typeof(employee))]
        public IHttpActionResult Deleteemployee(int id)
        {
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }

            db.employees.Remove(employee);
            db.SaveChanges();

            return Ok(employee);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool employeeExists(int id)
        {
            return db.employees.Count(e => e.EmployeeID == id) > 0;
        }
    }
}

Enable CORS on your WEBAPI

Open Nuget package console

Install-Package Microsoft.AspNet.WebApi.Cors
 config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));

Success

Let’s test these endpoints

Angular FE

Now install the Angular framework. I will be using version 7 that is why I have specified the version tag.

npm install -g @angular/cli@7.3.9

Create Angular CLI project

ng new emp-fe

Then start it up

ng serve --o

Components

Create an employees component

ng g c employees

Create an employee component

ng g c employees/employee
ng g s shared/employee
 ng g c employees/employee-list
ng g cl shared/employee --type=model

I will continue this a fresh Angular tutorial

Leave a Reply

Close Menu