CURD Operations Using ASP .Net Core Web API And ReactJS

In this article, we will discuss how to perform CURD operation in React JS and consume ASP.Net Core Web API to fetch student’s data.

We will create step by step instructions to perform CURD operation in React JS.

We recommend please read previous article before starting ReactJS CRUD opteration.

How to create ASP.NET Core Web Api

Prerequisite:

Section we need to follow:

  • Create React Application

Create React Application

Step 1: Open Terminal (Ctrl + ~).

Step 2: Select path where you want to create react application.

Step 3: PS C:\Vibersol\React> npx create-react-app sms

Step 4: If you are getting error while creating application like below:

Solution :

Step 5: Now the project structure look like below:

Step 6: Without any changes let see on the browser whether it is working or not.

PS C:\Vibersol\React\sms> npm start

working as expected.

Step 7 : Install Packages

  • npm install react-bootstrap bootstrap
  • npm install axios
  • npm install react-toastify
  • npm install semantic-ui-react semantic-ui-css

react-bootstrap installed for interface design, look and feel.

axios installed to communicate with the api. It provides more functionality and features that help you to build your application quickly.

react-toastify installed to notification in react application.

semantic-ui-react semantic-ui-css provides themes as CSS stylesheet.

Any packages you have installed in react application is showing in package.json file

Step 8 : Create new “Component” folder

  • src => Component

Step 9: Create new StudentList.js file inside the Component folder

  • src => Component => StudentList.js

Step 10 : Display the employee details in StudentList.js

import {Table,Col,Row, Container} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

function StudentList(props){
    return (
        <Container>
            <Row>
                <Col>
                    Id
                </Col>
                <Col>
                    Name
                </Col>
                <Col>
                    City
                </Col>
                <Col>
                    Qualification
                </Col>
                <Col>
                    Phone
                </Col>
            </Row>
            {
             //   props.students 
               Array.isArray(JSON.parse(props.students))? JSON.parse(props.students).map((stu)=>(
                <Row key={stu.sId}>
                    <Col>{stu.sName}</Col>
                    <Col>{stu.sCity}</Col>
                    <Col>{stu.sQualification}</Col>
                    <Col>{stu.sEmail}</Col>
                    <Col>{stu.sPhone}</Col>
                </Row>
               )):null
            }
            
            
        </Container>
    )
}
export default StudentList;
  • props : Get all Student Information.
  • Array.isArray : Check the information that hold in props is in array or not. If the information is in array then return true else return false.
  • map() : map function iterate the props array and accessing individual record.

Step 11 : Call GetStudentInfos api which has been created in previous tutorial

import logo from './logo.svg';
import './App.css';
import StudentList from './Component/StudentList';
import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const[Student,SetStudent] = useState([]);

  useEffect(()=>{
    let ignore = false;
    axios.get("https://localhost:7077/api/Student/GetStudentInfos").then((response)=>{
      if(!ignore){
        SetStudent(response.data);
      }
    })
    return ()=>{ignore=true}
  },[]);

  return(
    <StudentList students= {JSON.stringify(Student)} ></StudentList>
  )
}

export default App;

Here 2 hooks are using useEffect and useState

useEffect : React useEffect() hook is used to eliminate the side effects(out side of the scope of React) of using class based component. The task of useEffect hook is updating the DOM, fetching data from API, setting up subscription and timer etc.

Here you notice the useEffect() hook contains 2 arguments :

  • First Argument return called effect, is either return a function or undefined. Effect is executed when the component is render depend on some condition.
  • Second Argument is an array of dependencies. If you want to control the effect to execute when the component is render then pass the array of dependencies as a second argument. Here we have passed empty array that means we want effect to be executed only on first render.

useState : useState() hooks is the initial state that returns 2 values.

  • First Value : Student, current state that initially hold blank array.
  • Second Value : SetStudent, function that update current state.

For using both hooks need to import hooks from React

  • import { useEffect, useState } from ‘react’

axios : Axios allows you to communicate with the API in your React application. Here, axios using to get Student Information from API.

Step 12 : After executing the react application the record will look like below:

Step 13 : We can also use Semantic React UI instead of Bootstrap. To use Semantic React UI need to change some existing code:

StudentList.js

import 'bootstrap/dist/css/bootstrap.min.css';
import { Fragment } from 'react';
import { Table } from "semantic-ui-react";


function StudentList(props){
    return (
        <Fragment>
            <h1 style={{marginLeft:"30px"}}>
                Student List
            </h1>
            <Table celled style={{
                marginLeft:"30px",
                marginTop:"30px",
                width:"1050px",
                border :"1px solid black"
            }}>
            <Table.Header>
                <Table.Row>
                    <Table.HeaderCell>Id</Table.HeaderCell>
                    <Table.HeaderCell>Name</Table.HeaderCell>
                    <Table.HeaderCell>City</Table.HeaderCell>
                    <Table.HeaderCell>Qualification</Table.HeaderCell>
                    <Table.HeaderCell>Email</Table.HeaderCell>
                    <Table.HeaderCell>Phone</Table.HeaderCell>
                </Table.Row>
            </Table.Header>
            <Table.Body>
                {
                    Array.isArray(JSON.parse(props.students))? JSON.parse(props.students).map((stu)=>(
                        <Table.Row key={stu.sId}>
                            <Table.Cell>{stu.sId}</Table.Cell>
                            <Table.Cell>{stu.sName}</Table.Cell>
                            <Table.Cell>{stu.sCity}</Table.Cell>
                            <Table.Cell>{stu.sQualification}</Table.Cell>
                            <Table.Cell>{stu.sEmail}</Table.Cell>
                            <Table.Cell>{stu.sPhone}</Table.Cell>
                        </Table.Row>
                    )):null
                }
            </Table.Body>
        </Table>
        </Fragment>
    )
}
export default StudentList;

GridDisplay.js

import StudentList from './StudentList';
import {Grid} from 'semantic-ui-react';

function GridDisplay(props){
    return(
        <Grid>
            <Grid.Column width="10">
            <StudentList students={props.students}></StudentList>
            </Grid.Column>
        </Grid>
    );
}
export default GridDisplay;

App.js

import logo from './logo.svg';
import './App.css';
import GridDisplay from './Component/GridDisplay';
import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const[Student,SetStudent] = useState([]);

  useEffect(()=>{
    let ignore = false;
    axios.get("https://localhost:7077/api/Student/GetStudentInfos").then((response)=>{
      if(!ignore){
        SetStudent(response.data);
      }
    })
    return ()=>{ignore=true}
  },[]);

  return(
    <GridDisplay students= {JSON.stringify(Student)} ></GridDisplay>
  )
}
export default App;

After executing application the result look like below:

Step 14 : Add student’s record using interface. To insert details of student we required the form where user can submit the student details. After submitting the form request AddStudent api will call, before creating form we also require Add button where user click on the add button then Add Student form will be open.

Explore Technology

Blog Articles

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

CRUD operation Asp .Net Core with Entity Framework Data First Approach

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core. Using onion architecture our application becomes better testable, Flexible and Maintainable….

ASP .NET Core Web API and Database First Approach Best Practices

Introduction

In this article, we will discuss Onion Architecture with ASP .NET Core Web API and MySql Entity Framework Core (Database First Approach). Basically onion architecture provides us a better way to build application. Using this architecture our application becomes better testable, Flexible and Maintainable.

Onion Architecture in ASP .NET Core Web API
  • Domain Layer : Domain Layer basically a entity layer in which all database table exists.
  • Repository Layer : Repository is an abstraction of the data access layer. It hides the details of how exactly the data is saved or retrieved from the underlying data source.
  • Service Layer : A Service Layer is an additional layer that work as a mediator between controller and repository layer. A Service Layer contains business logic.
  • Presentation Layer : The Presentation Layer is the top most layer of the N-tier architecture used to display result to the user.

Table of Contents

Pre-requisites:

Now Create Database and Table in MySql Server

  • Open MySql Server.

Step 1: Create Database => Create Table

CREATE DATABASE SMS;

CREATE TABLE tbl_StudentInfo
(
s_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
s_name varchar(100),
s_city varchar(100),
s_qualification varchar(50),
s_email varchar(20),
s_phone varchar(10)
);

Step 2: I assume you have created a default Project API with WeatherForecastController. If not please see me.

Step 3: Add Core.Entity class library under the SMS Solution Explorer.

Right Click on the solution => Add =>New Project => Class Library

Step 4 : Add Entity Framework Tool and MySql Provider to Core.Entity class library.

Right click on Core.Entity=>Manage NuGetPackage

Go to Browse => In Search box type “Microsoft.EntityFrameworkCore.Tools” => Select Microsoft.EntityFrameworkCore.Tools => Install => Apply

Install MySql Server Provider “MySql.EntityFrameworkCore” same as “Microsoft.EntityFrameworkCore.Tools

Step 5 : Build the solution.

Step 6 : Provide project library[Core.Entity] reference to Core.SMS

Step 7: Double click on Core.Entity then csproj will be open. Comment the blow line.

Step 8 : Now using below Scaffold-DbContext command to create a model from existing database. Here you will notice we are creating model in separate class library.

Go to Package Manager Console:

PM> Scaffold-DbContext “Server=localhost;Database=SMS;port=3306;user=root;password=12345;”MySql.EntityFrameworkCore -OutputDir Model -Project “Core.Entity” -Tables tbl_StudentInfo -f

Here you can see SmsDbContext has been created in Model folder under the Core.Entity Project

Now remove the Connection String from here and place it into appsetting.json in Core.Entity

appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SMSConnection": "Server=localhost;Database=SMS;port=3306;user=root;password=12345;"
}
}

Step 9 : Add new project class library – Core.Service under SMS Solution Explorer.

Step 10 : Add new class IRepositoryBaseService in Core.Service project class library.

Create generic repository base service interface IRepositoryBaseService where <T> indicates class name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Core.Service
{
public interface IRepositoryBaseService<T>
{
IQueryable GetAllRecords();
IQueryable GetFilterRecords();
void CreateRecord(T entity);
void UpdateRecord(T entity);
void DeleteRecord(T entity); } }

Step 11 : Create IStudentInfoService interface and inherit to the IRepositoryBaseService

using Core.Entity.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Service
{
     public interface IStudentInfoSevice : IRepositoryBaseService<TblStudentinfo>
    {
          IEnumerable GetStudentInfos();
          IEnumerable BetStudentInfoByConditoin(TblStudentinfo tblStudentinfo);
          void CreateStudent(TblStudentinfo entity);
          void UpdateStudent(TblStudentinfo entity);
          void DeleteStudent(TblStudentinfo entity);
    }
}

Step 12 : Create IRepositoryWrapperService interface to store all table repository service interface.

namespace Core.Service
{
    public interface IRepostoryWrapperService
    {
        IStudentInfoSevice studentInfoSevice { get; }
    }
}

Step 13 : Next we have to implement the interface inside the Repository Class Library. Create RepositroyBaseService class inside the SMS project solution.

Add project reference Core.Service to Repository.

Implement IRepositoryBaseService interface in RepositoryBaseService class that is Abstract class.

using Core.Entity.Model;
using Core.Service;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Repository
{
    public abstract class RepositoryBaseService<T> : IRepositoryBaseService<T> where T : class
    {
        private SmsContext _context;
        public RepositoryBaseService(SmsContext context)
        {
            _context = context;
        }

        public IQueryable<T> GetAllRecords() { 
            return  _context.Set<T>().AsNoTracking();
        }
        public IQueryable<T> GetFilterRecords(Expression<Func<T, bool>> expression)
        {
            return _context.Set<T>().Where(expression).AsNoTracking();
        }
        public void CreateRecord(T entity)
        {
            _context.Set<T>().Add(entity);
        }
        public void UpdateRecord(T entity)
        {
            _context.Set<T>().Update(entity);
        }
        public void DeleteRecord(T entity)
        {
            _context.Set<T>().Remove(entity);
        }
    }
}

Step 14 : Add new class StudentInfoService to implement RepositoryBaseService and IStudentInfoSevice interface inside the Repository.

using Core.Entity.Model;
using Core.Service;
using Microsoft.EntityFrameworkCore;

namespace Repository
{
    public class StudentInfoService : RepositoryBaseService<TblStudentinfo>,IStudentInfoSevice
    {
        public StudentInfoService(SmsContext smsContext):base(smsContext) 
        {
            
        }
       public IEnumerable<TblStudentinfo> GetStudentInfos()
        {
            return GetAllRecords().OrderBy(m => m.SName).ToList();
        }
       public IEnumerable<TblStudentinfo> GetStudentInfoByCondition(Guid SId)
        {
            return GetFilterRecords(m => m.SId.Equals(SId)).ToList();
        }
       public void CreateStudent(TblStudentinfo entity) 
       {
            CreateRecord(entity);
       }
       public void UpdateStudent(TblStudentinfo entity) 
       {
            UpdateRecord(entity);
       }
       public void DeleteStudent(TblStudentinfo entity) 
       {
            DeleteRecord(entity);
       }
    }
}

Step 15 : Now Create RepositoryWrapperService to implement IRepostoryWrapperService.

using Core.Entity.Model;
using Core.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace Repository
{
    public class RepositoryWrapperService : IRepostoryWrapperService
    {
        private SmsContext context;
        private IStudentInfoSevice studentInfo;
        public RepositoryWrapperService(SmsContext smsContext) 
        {
            context = smsContext;    
        }

        public IStudentInfoSevice studentInfoSevice
        {
            get
            {
                if(studentInfo == null)
                {
                    studentInfo = new StudentInfoService(context);
                }
                return studentInfo;
            }
        }
    }
}

Step 16 : Create Controller under the Core.SMS Project file.

Right click on Controller folder => Add=>Controller

Under the Common section select API => select API controller-Empty => Click Add

Rename the ValueController to StudentController.

Add Core.Service project reference to Core.SMS Project.

Now get all student records :

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Core.Service;
using Core.Entity.Model;

namespace Core.SMS.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private IRepostoryWrapperService _repostoryWrapperService;
        private SmsContext SmsContext;
        public StudentController(IRepostoryWrapperService repostoryWrapperService, SmsContext smsContext)
        {
           _repostoryWrapperService = repostoryWrapperService;
           SmsContext = smsContext;
        }
        [HttpGet]
        public IActionResult GetStudentInfos()
        {
            var students = _repostoryWrapperService.studentInfoSevice.GetAllRecords();
            return Ok(students);
        }
    }
}

Step 17: Go to Program.cs class to register IRepostoryWrapperService and RepositoryWrapperService. No need to register all the Services because here WrapperService work as a parent service.

Configure your connection string in Program.cs

var connectionString = builder.Configuration[“ConnectionStrings:SMSConnection”];
builder.Services.AddDbContext<SmsContext>(option => option.UseMySQL(connectio
n));

Lifecycle

  • Transient :- Transient objects are always different, a new instance is provided to every controller and every service.
  • Scope :- A scope is typically associated with a single HTTP request. The same instance is shared within the same scope, but different scopes will have different instances.
  • Singleton :- A Singleton objects are the same for every object and every request.
using Core.Entity.Model;
using Core.Service;
using Microsoft.EntityFrameworkCore;
using Repository;

var builder = WebApplication.CreateBuilder(args);


var connectionString = builder.Configuration["ConnectionStrings:SMSConnection"];
builder.Services.AddDbContext<SmsContext>(option => option.UseMySQL(connectionString));

// Add services to the container.
builder.Services.AddScoped<IRepostoryWrapperService, RepositoryWrapperService>();
//builder.Services.AddScoped<IStudentInfoSevice, StudentInfoService>();

//Add Controller
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

//Set Cors Policy
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
     builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
});

//Add Swagger Functionality
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

//Allow Cors
app.UseCors("CorsPolicy");

app.Run();

Execute your API and See the Result:

Now Add Student information to tbl_StudentInfo table:

[HttpPost]
public IActionResult AddStudent(TblStudentinfo tblStudentinfo)
{
    try
    {
        _repostoryWrapperService.studentInfoSevice.CreateStudent(tblStudentinfo);
        SmsContext.SaveChanges();
        return Ok();
        
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

Now Update Student information to tbl_StudentInfo table:

[HttpPost]
public IActionResult UpdateStudent(TblStudentinfo tblStudentinfo)
{
    try
    {
        _repostoryWrapperService.studentInfoSevice.UpdateStudent(tblStudentinfo);
        SmsContext.SaveChanges();
        return Ok();

    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }

}

Now Delete Record from tbl_StudentInfo :

[HttpPost]
public IActionResult DeleteStudent(TblStudentinfo tblStudentinfo)
{
    try
    {
        _repostoryWrapperService.studentInfoSevice.DeleteRecord(tblStudentinfo);
        SmsContext.SaveChanges();
        return Ok();

    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

Related Topics

How to consume Dot Net Core API in React Application.

ASP.Net Core API

Introduction

In this Article, We will discuss about Asp.net Core Web Api. After reading this article you will completely aware with Web Api. At the end of the topics some interview Q&A are available.

Let’s Start :

Topics that will cover in this article is mentioned below :

  • What is API?
  • Why Web Api is popular than previous Api ?
  • Why Web Api is required?
  • How to create Web Api in Asp.net Core?

What is API ?

Application Programming Interface(API) is an intermediate software agent used to communicate between more than one applications with the help of HTTP Method.

In above diagram, API is directly connected with database and Web application or Mobile Application connected with the API. API can take the request from multiple source (Web Browser, Phone Devices or Google devices) and passes all request to the Database(SQL, MySQL, Oracle, NoSQL, MongoDb etc..) . Database process the request and passes response to the API. Now API get the response and provides the result to requesting devices.

Why Web API is popular than other API ?

Web API supports various formats like JSON, XML, BSON and url-encoded data. User just need to pass content-type to get expected result format otherwise by default Web API return result in XML format.

Web API use model-view-controller(MVC) architecture that allows better separation of concern that means it keep’s separate data access layer(DAL) from business access layer(BAL);

  • How to Get JSON Result ?

GET http://localhost:15192/api/customer/1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:15154
Content-Type: application/json

  • How to Get XML Result ?

GET http://localhost:15192/api/customer/1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:15154
Content-Type: application/xml

  • How to Get BSON Result ?

GET http://localhost:15192/api/customer/1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:15154
Content-Type: application/bson

  • How to Get URL-Encoded Data ?

GET http://localhost:15192/api/customer/1 HTTP/1.1
User-Agent: Fiddler
Host: localhost:15154
Content-Type: application/x-www-form-urlencoded

Why Web API Required ?

As we discussed, the user wants to access the result from different-2 devices like web browser, mobile, google devices etc. Here, Web API is works as a centralized services that takes request from multiple platform and passes the corresponding output.

How to create Web API in Asp.net Core ?

Step 1 : Install Visual Studio

Step 2 : Open Visual Studio => Create a new project

Step 3 : Select ASP.NET Core Web API => Click Next

Step 4: Configure your new project

  • Project Name : Enter your project name
  • Location: Browse your path where you want to save the project.
  • Solution Name : Enter the name of the solution where entire projects will store. By Default Project name and Solution name is same.

Step 5: Additional Information

  • Framework : Select Target Framework.
  • Authentication Type: None, Microsoft Identity Platform, Windows.
  • None : No authentication Required.
  • Microsoft Identity Platform : Authenticate with Microsoft Azure Active Directory. Azure AD creates and manages credentials that help enterprise user sign-in and access both internal and external resources.
  • Window Authentication : Users are authenticate with the help of Operating System. It is useful in intranet application where user are in the same domain.

Step 6: By Default Microsoft has created one API(WeatherForecast). You can see the project structure:

Step 7: Lets execute(F5) the API without making any changes.

By Default Weather API is executed with the help of Swagger. It is an open source software tool to design, build and use RESTFul web api. Generally Web Api uses HTTP VERBS for (Create, Read, Edit and Delete) operation.

  • HTTP GET: Read Operation.
  • HTTP POST: Create Operation.
  • HTTP PUT: Update Operation.
  • HTTP DELETE: Delete Operation.

Related Topics