Angular CRUD with .NET Core API

By Rasyue | On January 22, 2023

angular crud
angular crud .net core api

Introduction

In this tutorial Angular CRUD with .NET Core API, we will be learning how to create a CRUD application with Angular and ASP.NET Core Web API along with MySQL Database.

Angular CRUD with .NET Core API: Setting Up The .NET Core API

First of all, make sure you already have Visual Studio Community Edition installed.

Open it and create a new project.

Angular CRUD with .NET Core API
ASP.NET CORE Web API

Finish the create new project wizard and then run the application.

You will have the default WeatherForecast Web API application.

Before we can go further with our API application, first let’s prepare our MySQL DB and table.

Angular CRUD with .NET Core API: Create MySQL Database and Table

We are using XAMPP for this tutorial. You can use others if you wish.

Open phpmyadmin and create a new database, rasyuenet or any other name as you wish.

Then, create a table book like below.

mysql table
create table in phpmyadmin

Insert a couple of books entry.

mysql
Insert rows

All done with MySQL table. Let’s go back the .NET Core Web API.

Angular CRUD with .NET Core API: Creating API Endpoints

Rename the WeatherForecastController.cs to BookController.cs. Also rename the WeatherForecast.cs to Book.cs.

Building the Controller

Copy and paste this into your new BookController.cs

using Microsoft.AspNetCore.Mvc;
using MySqlConnector;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class BookController : ControllerBase
    {
 

        private readonly IConfiguration _configuration;

        private readonly ILogger<BookController> _logger;

        public BookController(
            ILogger<BookController> logger, 
            IConfiguration configuration
            )
        {
            _logger = logger;
            _configuration = configuration;
        }

        [HttpGet]
        public List<Book> Get()
        {
           
            List<Book> list = new List<Book>();
            string sqlDataSource = _configuration.GetConnectionString("Default");
            using (MySqlConnection conn = new MySqlConnection(sqlDataSource))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("select * from book", conn);

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(new Book()
                        {
                            id = (int)reader["id"],
                            BookName = reader["BookName"].ToString(),
                            BookDesc = reader["BookDesc"].ToString(),
                            BookAuthor = reader["BookAuthor"].ToString()

                        });
                    }
                }
            }
            return list;

        }

        [HttpGet("{id}")]
        public Book Get(int id) {

            string sqlDataSource = _configuration.GetConnectionString("Default");
            Book book = new Book();
            using (MySqlConnection conn = new MySqlConnection(sqlDataSource))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("select * from book WHERE id ="+ id.ToString(), conn);
             
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        book = new Book()
                        {
                            id = (int)reader["id"],
                            BookName = reader["BookName"].ToString(),
                            BookDesc = reader["BookDesc"].ToString(),
                            BookAuthor = reader["BookAuthor"].ToString()
                        };
                    }
                }
            }
            return book;
        }

        [HttpPost]
        public int Post([FromBody] Book res) {
            string sqlDataSource = _configuration.GetConnectionString("Default");
            var result = 0;
            MySqlConnection conn = new MySqlConnection(sqlDataSource);
            try
            {

                conn.Open();

                var BookName = res.BookName;
                var BookDesc = res.BookDesc;
                var BookAuthor = res.BookAuthor;

                string sql = "INSERT INTO `book` (BookName, BookDesc, BookAuthor) " +
                    "VALUES ('"+ BookName + "'," +
                    "'"+BookDesc+"'" + ", '"+ BookAuthor + "')";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                result = cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            conn.Close();
            return result;

        }

        [HttpPut]
        public int Put([FromBody] Book res)
        {
            string sqlDataSource = _configuration.GetConnectionString("Default");
            var result = 0;
            MySqlConnection conn = new MySqlConnection(sqlDataSource);
            try
            {

                conn.Open();

                var BookId = res.id;
                var BookName = res.BookName;
                var BookDesc = res.BookDesc;
                var BookAuthor = res.BookAuthor;

                string sql = "UPDATE `book` SET `BookName`='"+ BookName + "',`BookDesc`='"+ BookDesc + "',`BookAuthor`='"+ BookAuthor + "' WHERE id =" +BookId;
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                result = cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            conn.Close();
            return result;

        }

        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            string sqlDataSource = _configuration.GetConnectionString("Default");
            var result = 0;
            MySqlConnection conn = new MySqlConnection(sqlDataSource);
            try
            {

                conn.Open();

                string sql = "DELETE FROM `book` WHERE id =" + id;
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                result = cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            conn.Close();

        }


    }
}

In the BookController.cs, we define one endpoint or route that accepts 4 different HTTP methods, namely GET, POST, PUT, and DELETE.

From the controller, we are also fetching, posting and deleting data from the MySQL database.

Usually, we will need to define a repository for database related functions for each controller and method but for the sake of simplicity, we will be using this controller to do the job.

Building the Model

Copy and paste this into Book.cs

namespace WebApplication1
{
    public class Book
    {
        public int id { get; set; }
        public string BookName { get; set; }
        public string BookDesc { get; set; }

        public string BookAuthor { get; set; }

    }
}

Nothing too fancy here in the Model. We are just defining the field for the Book Model. You can add more fields if you wish but remember to also modify your MySQL table and the controller as well.

Start the ASP.NET Core Web API and you should have something like this.

ASP.NET Core Swagger

One last thing before we are done, we need to define our MySQL connection string.

MySQL Connection String

Open appsettings.json and paste the followings.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Default": "Server=127.0.0.1;User ID=root;Password=;Database=rasyuenet"
  }
}

Adjust the connection string accordingly.

That’s it for the Web API. Moving on to the Angular UI.

Angular CRUD with .NET Core API: Setting Up The Angular UI

To create a new Angular project, run below command.

npm i -g @angular/cli 
ng new rasyue
cd rasyue
npm start

You will have a new basic Angular project running at localhost:4200

Let’s design a simple UI for CRUD operations.

Copy and paste the followings into app.component.html

<div>
  <button (click)="isCreate=true;">Create Book</button>
</div>

<div *ngIf="!isCreate && !isEdit">
  <table style="border: 1px solid black; margin: 30px 0 0 30px;">
    <thead>
      <tr>
        <td width="100px">Number</td>
        <td width="200px">Name</td>
        <td width="300px">Description</td>
        <td width="200px">Author</td>
        <td width="100px">Action</td>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let book of this.booksArray">
        <td>{{book.id}}</td>
        <td>{{book.bookName}}</td>
        <td>{{book.bookDesc}}</td>
        <td>{{book.bookAuthor}}</td>
        <td>
          <button (click)="edit(book)">Edit</button>
          <button (click)="deleteBook(book.id)">Delete</button>
        </td>

      </tr>
    </tbody>
  </table>
</div>



<div *ngIf="isCreate" style="margin-top: 50px;">
  <input [(ngModel)]="newBookName" type="text" placeholder="Book Name" />
  <input [(ngModel)]="newBookDesc"  type="text" placeholder="Book Description" />
  <input [(ngModel)]="newBookAuthor"  type="text" placeholder="Book Author" />
  <button (click)="createNewBook()">Create New Book</button>
</div>


<div *ngIf="isEdit" style="margin-top: 50px;">
  <input [(ngModel)]="editBookName" type="text"/>
  <input [(ngModel)]="editBookDesc" type="text"/>
  <input [(ngModel)]="editBookAuthor" type="text"/>
  <button (click)="editBook()">Edit Book</button>

</div>

Next, we need to define our methods, variables etc in the typescript file.

Open app.component.ts and paste the followings.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  title = 'rasyue';
  apiURL = 'https://localhost:7081/'
  isCreate: boolean = false
  isEdit: boolean = false

  newBookName: string = ''
  newBookDesc: string = ''
  newBookAuthor: string = ''

  
  editId: number = 0
  editBookName: string = ''
  editBookDesc: string = ''
  editBookAuthor: string = ''

  booksArray: {id: number, bookName: string, bookDesc: string, bookAuthor: string}[] = []

  constructor(
    private httpClient: HttpClient
  ){

    this.httpClient.get(`${this.apiURL}Book`)
    .subscribe((resp: any) => {
      this.booksArray = resp

    })


  }

  createNewBook(){
   
    this.httpClient.post(`${this.apiURL}Book`,
      {
        BookName: this.newBookName,
        BookDesc: this.newBookDesc,
        BookAuthor: this.newBookAuthor,

      })
    .subscribe(() => {

      this.httpClient.get(`${this.apiURL}Book`)
      .subscribe((resp: any) => {
        this.booksArray = resp
  
      })
  
    })

    this.isCreate=false
    this.newBookName = ''
    this.newBookDesc = ''
    this.newBookAuthor = ''

  }

  
  editBook(){
    this.httpClient.put(`${this.apiURL}Book`,
    {
      id: this.editId,
      BookName: this.editBookName,
      BookDesc: this.editBookDesc,
      BookAuthor: this.editBookAuthor,

    })
    .subscribe(() => {

      this.httpClient.get(`${this.apiURL}Book`)
      .subscribe((resp: any) => {
        this.booksArray = resp

      })

    })

    this.isEdit=false
    this.editId = 0
    this.editBookName = ''
    this.editBookDesc = ''
    this.editBookAuthor = ''

  }

  deleteBook(id: number){
    this.httpClient.delete(`${this.apiURL}Book/${id}`)
    .subscribe(() => {
      this.httpClient.get(`${this.apiURL}Book`)
      .subscribe((resp: any) => {
        this.booksArray = resp

      })

    })
  }

  edit(input: {id: number, bookName: string, bookDesc: string, bookAuthor: string}){

    this.editId = input.id
    this.editBookName = input.bookName
    this.editBookDesc = input.bookDesc
    this.editBookAuthor = input.bookAuthor

    this.isEdit = true
  }

}

And we are done with the Angular UI.

Now, let’s test our application.

Book Page

Angular CRUD with .NET Core API
book page

Create New Book

Angular CRUD with .NET Core API
create new book

Edit Book

Angular CRUD with .NET Core API
edit book

And there you have it.

The End

If you are interested to learn more about .NET Core, then check out this tutorial or if you are more interested in Angular then check this out.