Monday, October 11, 2021

CRUD Operations Using ReactJS Hooks and Web API

Introduction 

Hooks are a new concept that was introduced in React 16.8. Hooks are an alternative to classes. 

In this article, I'm going to create CRUD operations using React Hooks and Web API.


Prerequisites

Basic knowledge of React.js and Web API.

Visual Studio should be installed on your system.

SQL Server Management Studio.

Basic knowledge of React strap and HTML.


Create a ReactJS Project

Let's create a React app by using the following command:

npx create-react-app crudhooks  

Open the newly created project in Visual Studio Code and install Reactstrap and Bootstrap in this project by using the following commands.

npm install --save bootstrap    

npm install --save reactstrap react react-dom 


Now, open the index.js file and add import Bootstrap.

import 'bootstrap/dist/css/bootstrap.min.css'; 


Now, install the Axios library by using the following command.

npm install --save axios    


Now, go to the src folder,  create a new folder, and inside this folder, add three new components:

Createemployee.js.

Editemployee.js.

EmployeList.js.


Add Routing in ReactJS

Install the react-router-dom package by using the following command:

npm install react-router-dom --save 


Open the app.js file and import Router, Route (react-router-dom), and the three components

Add the following code in the app.js file:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Switch, Route, Link }
        from 'react-router-dom';
import Createemployee from './components/Createemployee'
import EmployeList from './components/EmployeList'
import Editemployee from "./components/Editemployee";

function App() {  
    return (
      <div className="App">
       <Router>
        <div className="container">  
          <nav className="btn btn-warning navbar navbar-expand-lg navheader">  
            <div className="collapse navbar-collapse" >  
              <ul className="navbar-nav mr-auto">
                <li className="nav-item">
                  <Link to={'/Createemployee'}
                    className="nav-link">Add Employee</Link>
                </li>
                <li className="nav-item">
                  <Link to={'/EmployeList'}
                    className="nav-link">Employee List</Link>
                </li>    
              </ul>
            </div>
          </nav> <br />
          <Switch>  
            <Route exact path='/Createemployee' component={Createemployee} />  
            <Route path='/edit/:id' component={Editemployee} />  
            <Route path='/EmployeList' component={EmployeList} />    
          </Switch>    
        </div>    
      </Router>  
      </div>
    );  
  }  
  export default App;  

Now, open the Createemployee.js file and add the following code:

import React, { useState, useEffect } from 'react'  
import axios from 'axios';
import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup,
        InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
function Createemployee(props) {  
  const [employee, setemployee] = useState({ Name: '', Department: '', Age: '',
        City: '', Country: '', Gender: '' });
  const [showLoading, setShowLoading] = useState(false);  
  const apiUrl = "http://localhost:62168/api/Hooks/CreateEmp";  

  const Insertemployee = (e) => {  
    e.preventDefault();
    debugger;  
    const data = { Name:employee.Name, Department: employee.Department,
                    Age: employee.Age, City:employee.City,
                    Country: employee.Country, Gender: employee.Gender };
    axios.post(apiUrl, data)  
      .then((result) => {  
        props.history.push('/EmployeList')  
      });  
  };  
  const onChange = (e) => {
    e.persist();  
    debugger;
    setemployee({...employee, [e.target.name]: e.target.value});
  }  

  return (  
    <div className="app flex-row align-items-center">  
      <Container>  
        <Row className="justify-content-center">  
          <Col md="12" lg="10" xl="8">
            <Card className="mx-4">  
              <CardBody className="p-4">  
                <Form onSubmit={Insertemployee}>
                  <h1>Register</h1>  
                  <InputGroup className="mb-3">  
                    <Input type="text" name="Name" id="Name" placeholder="Name"
                    value={employee.Name} onChange={ onChange }  />
                  </InputGroup>  
                   <InputGroup className="mb-3">
                    <Input type="text" placeholder="Department" name="Department"
                        id="Department" value={employee.Department}
                        onChange={ onChange }/>  
                  </InputGroup>
                  <InputGroup className="mb-3">
                    <Input type="text" placeholder="Age" name="Age" id="Age"  
                        value={employee.Age} onChange={ onChange }  />  
                  </InputGroup>  
                  <InputGroup className="mb-4">  
                    <Input type="text" placeholder="City" name="City" id="City"
                        value={employee.City} onChange={ onChange }  />
                  </InputGroup>  
                  <InputGroup className="mb-4">  
                    <Input type="text" placeholder="Country" name="Country"
                        id="Country" value={employee.Country}
                        onChange={ onChange } />  
                  </InputGroup>
                  <InputGroup className="mb-4">  
                     <Input type="text" placeholder="Gender" name="Gender"
                        id= "Gender" value={employee.Gender}
                        onChange={ onChange } />  
                  </InputGroup>
             <CardFooter className="p-4">
                <Row>  
                  <Col xs="12" sm="6">  
                    <Button type="submit" className="btn btn-info mb-1" block>
                    <span>Save</span></Button>  
                  </Col>  
                  <Col xs="12" sm="6">
                    <Button className="btn btn-info mb-1" block>
                        <span>Cancel</span></Button>
                  </Col>  
                </Row>  
              </CardFooter>
                </Form>
              </CardBody>  
            </Card>  
          </Col>
        </Row>
      </Container>
    </div>  
  )  
}  

export default Createemployee  

Now, open the EmployeList.js file and add the following code:

import React from 'react'  
import { Badge, Card, CardBody, CardHeader, Col, Pagination, PaginationItem,
            PaginationLink, Row, Table } from 'reactstrap';
import axios from 'axios';
import { useState, useEffect } from 'react'  
function EmployeList(props) {  
  const [data, setData] = useState([]);

  useEffect(() => {  
    const GetData = async () => {
      const result = await axios('http://localhost:62168/api/hooks/employee');
      setData(result.data);
    };

    GetData();
  }, []);  
  const deleteeployee = (id) => {  
    debugger;
    axios.delete('http://localhost:62168/api/hooks/Deleteemployee?id=' + id)  
      .then((result) => {  
        props.history.push('/EmployeList')  
      });  
  };  
  const editemployee = (id) => {
    props.history.push({
      pathname: '/edit/' + id
    });
  };  

  return (  
    <div className="animated fadeIn">  
      <Row>  
        <Col>
          <Card>  
            <CardHeader>
              <i className="fa fa-align-justify"></i> Employee List  
              </CardHeader>  
            <CardBody>  
              <Table hover bordered striped responsive size="sm">  
                <thead>
                  <tr>  
                    <th>Name</th>  
                    <th>Department</th>  
                    <th>Age</th>
                    <th>City</th>
                    <th>Country</th>  
                    <th>Gender</th>  
                    <th>Action</th>
                  </tr>
                </thead>  
                <tbody>
                  {  
                    data.map((item, idx) => {  
                      return <tr>
                        <td>{item.Name}</td>  
                        <td>{item.Department}</td>
                        <td>{item.Age}</td>
                        <td>{item.City}</td>  
                        <td>{item.Country}</td>
                        <td>{item.Gender}</td>  
                        <td>
                          <div class="btn-group">
                            <button className="btn btn-warning"
                                onClick={() => { editemployee(item.Id) }}>
                                Edit</button>  
                            <button className="btn btn-warning"
                                onClick={() => { deleteeployee(item.Id) }}>
                                Delete</button>
                          </div>  
                        </td>
                      </tr>
                    })}  
                </tbody>  
              </Table>  
            </CardBody>  
          </Card>  
        </Col>
      </Row>  
    </div>
  )
}  

export default EmployeList  

Now, open the Editemployee.js file and add the following code:

import React, { useState, useEffect } from 'react'
import axios from 'axios';  
import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input,
            InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
function Editemployee(props) {  
        const [employee, setemployee]= useState({Id:'',Name: '', Department: '',
                Age: '', City: '', Country: '', Gender: '' });  
        const Url = "http://localhost:62168/api/Hooks/employeedetails?id=" +
            props.match.params.id;  

        useEffect(() => {  
          const GetData = async () => {
            const result = await axios(Url);  
            setemployee(result.data);  

          };  

          GetData();
        }, []);  

        const UpdateEmployee = (e) => {
          e.preventDefault();  
          const data = {Id:props.match.params.id, Name:employee.Name,
                        Department: employee.Department, Age: employee.Age,
                        City:employee.City, Country: employee.Country,
                        Gender: employee.Gender };  
          axios.post('http://localhost:62168/api/Hooks/CreateEmp', data)  
            .then((result) => {
              props.history.push('/EmployeList')  
            });  
        };  

        const onChange = (e) => {  
          e.persist();
          setemployee({...employee, [e.target.name]: e.target.value});  
        }  

        return (
<div className="app flex-row align-items-center">  
<Container>  
<Row className="justify-content-center">
<Col md="12" lg="10" xl="8">  
<Card className="mx-4">  
<CardBody className="p-4">  
<Form onSubmit={UpdateEmployee}>
<h1>Update Employee</h1>
<InputGroup className="mb-3">  
<Input type="text" name="Name" id="Name"
placeholder="Name" value={employee.Name}
onChange={ onChange }  />  
</InputGroup>  
<InputGroup className="mb-3">  
<Input type="text" placeholder="Department"
name="Department" id="Department"
value={employee.Department} onChange={ onChange }/>
</InputGroup>
<InputGroup className="mb-3">
<Input type="text" placeholder="Age" name="Age"
id="Age"  value={employee.Age}
onChange={ onChange }  />
</InputGroup>  
<InputGroup className="mb-4">  
<Input type="text" placeholder="City" name="City"
id="City" value={employee.City}
onChange={ onChange }  />  
</InputGroup>  
<InputGroup className="mb-4">
<Input type="text" placeholder="Country" name="Country"
id="Country" value={employee.Country}
onChange={ onChange } />  
</InputGroup>  
<InputGroup className="mb-4">  
<Input type="text" placeholder="Gender" name="Gender"
id= "Gender" value={employee.Gender}
onChange={ onChange } />  
</InputGroup>  
<CardFooter className="p-4">  
<Row>
<Col xs="12" sm="6">  
<Button type="submit" className="btn btn-info mb-1" block>
<span>Save</span></Button>  
</Col>  
<Col xs="12" sm="6">  
<Button className="btn btn-info mb-1" block>
<span>Cancel</span></Button>  
</Col>  
</Row>
</CardFooter>
</Form>
</CardBody>  
</Card>  
</Col>
</Row>  
</Container>  
</div>  
        )  
}  

export default Editemployee  

Create a Table in the Database 

Open SQL Server Management Studio, create a database named "dbcore," and in this database, create a table. Give that table a name like "Employees."



CREATE TABLE [dbo].[Employees](  

    [Id] [int] IDENTITY(1,1) NOT NULL, 

    [Name] [nvarchar](50) NULL, 

    [Department] [nvarchar](50) NULL,

    [Age] [int] NULL,  

    [City] [nvarchar](50) NULL,  

    [Country] [nvarchar](50) NULL,  

    [Gender] [nvarchar](50) NULL,  

 CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED  

(  

    [Id] 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 



Create a Asp.net Web API project

Now, open Visual Studio and create a new project.

Change the name to ReactHooks.

Make Web API the template.

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

Click on the ADO.NET Entity Data Model option and click Add.

Select EF Designer from the database and click the Next button. Add the connection properties, select database name on the next page, and click OK.

Check the Table checkbox. The internal options will be selected by default. Now, click the Finish button. 


Now, our data model is successfully created.


Right-click the Models folder and add two classes — Emp and Response. Now, paste the following codes in these classes:


Emp class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;


namespace ReactHooks.Models

{

    public class Emp

    {

        public int Id { get; set; }


        public string Name { get; set; }


        public string Department { get; set; }


        public int Age { get; set; }


        public string City { get; set; }


        public string Country { get; set; }


        public string Gender { get; set; }

    }

}

Response Class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;


namespace ReactHooks.Models

{

    public class Response

    {

        public string Status { get; set; }


        public string Message { get; set; }

    }

}

Right-click the Controllers folder and add a new controller. Name it "Hooks controller".


Complete Hooks Controller Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using ReactHooks.Models;


namespace ReactHooks.Controllers

{

    [RoutePrefix("Api/Hooks")]

    public class HooksController : ApiController

    {

        CrudDemoEntities DB = new CrudDemoEntities();


        [HttpPost]

        public object CreateEmp(Emp e)

        {

            try

            {

                if (e.Id == 0)

                {

                    Employee em = new Employee();

                    em.Name = e.Name;

                    em.Department = e.Department;

                    em.Age = e.Age;

                    em.City = e.City;

                    em.Country = e.Country;

                    em.Gender = e.Gender;

                    DB.Employees.Add(em);

                    DB.SaveChanges();

                    return new Response

                    {

                        Status = "Success",

                        Message = "Data Successfully"

                    };

                }

                else

                {

                    var obj = DB.Employees.Where(x => x.Id == e.Id).ToList().FirstOrDefault();

                    if (obj.Id > 0)

                    {

                        obj.Name = e.Name;

                        obj.Department = e.Department;

                        obj.Age = e.Age;

                        obj.City = e.City;

                        obj.Country = e.Country;

                        obj.Gender = e.Gender;

                        DB.SaveChanges();

                        return new Response

                        {

                            Status = "Updated",

                            Message = "Updated Successfully"

                        };

                    }

                }

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            return new Response

            {

                Status = "Error",

                Message = "Data not insert"

            };

        }


        [HttpGet]

        [Route("employee")]

        public object Getrecord()

        {

            var emp = DB.Employees.ToList();

            return emp;

        }


        [HttpDelete]

        public object Deleteemployee(int id)

        {

            var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();

            DB.Employees.Remove(obj);

            DB.SaveChanges();

            return new Response

            {

                Status = "Delete",

                Message = "Delete Successfuly"

            };

        }


        [Route("employeedetails")]

        [HttpGet]

        public object employeedetailById(int id)

        {

            var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();

            return obj;

        }

    }

}

Now, let's enable CORS. Go to Tools, open the NuGet Package Manager, search for "CORS," and install the Microsoft.Asp.Net.WebApi.Cors package. Open Webapiconfig.cs and add the following lines:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Web.Http;

using Microsoft.Owin.Security.OAuth;

using Newtonsoft.Json.Serialization;

using System.Web.Http.Cors;


namespace ReactHooks

{

    public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

            // Web API configuration and services

            // Configure Web API to use only bearer token authentication.

            config.SuppressDefaultHostAuthentication();

            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


            // Web API routes

            config.MapHttpAttributeRoutes();


            config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{id}",

                defaults: new { id = RouteParameter.Optional }

            );


            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);

        }

    }

}


Now, go to VS Code and run the project by using following command Npm start and check the port that you have your application running on. 


Enter some data in the textbox and click on the Save button.


Click the Edit button to update values or the Delete button to delete the value. 


Friday, October 8, 2021

CRUD Operations Using ReactJS and ASP.NET Web API

 Introduction 

Here  I'm going to perform CRUD operations using  React.js and ASP.NET Web API. ReactJS is an open-source JavaScript library that is used for creating user interfaces. It is developed and maintained by Facebook.

Prerequisites:

We should have the basic knowledge of React.js and Web API.

Visual Studio and Visual Studio Code IDE should be installed on your system.

SQL Server Management Studio.

Technologies we will use:

ASP.NET Web API.

ReactJS.

SQL Server.

React strap.

Bootstrap.


Create a Table in the Database

Open SQL Server Management Studio, create a database named "CrudDemo," and in this database, create a table. Give that table a name like "studentmaster."


USE [CrudDemo]  

GO  

CREATE TABLE [dbo].[studentmaster](  

    [Id] [int] IDENTITY(1,1) NOT NULL,  

    [Name] [varchar](50) NULL,  

    [RollNo] [varchar](50) NULL,  

    [Class] [varchar](50) NULL,  

    [Address] [varchar](50) NULL,  

 CONSTRAINT [PK_studentmaster] PRIMARY KEY CLUSTERED   

(  

    [Id] 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  

Create a New Web API Project

Create a New Project. 



Change the Name to CrudUsingReact

Choose the Web API Template

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

Click on the "ADO.NET Entity Data Model" option and click "Add."

Select EF Designer from the database and click the "Next" button.

Add the connection properties and select database name on the next page and click OK.

Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button. 

Right-click on Models folder and add two classes — Student and Response. Now, paste the following codes in these classes:

public class Student  {  

       public string Name { get; set; }  

       public string Rollno { get; set; }  

       public string Class { get; set; }  

       public string Address { get; set; }  

   }  


public class Response  {  

       public string Status { get; set; }  

       public string Message { get; set; }  

   } 


Right-click on the Controllers folder and add a new controller. Name it "Student controller"


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using CrudUsingReact.Models;


namespace CrudUsingReact.Controllers

{

    [RoutePrefix("Api/Student")]

    public class studentController : ApiController

    {

        CrudDemoEntities DB = new CrudDemoEntities();

        [Route("AddotrUpdatestudent")]

        [HttpPost]

        public object AddotrUpdatestudent(Student st)

        {

            try

            {

                if (st.Id == 0)

                {

                    studentmaster sm = new studentmaster();

                    sm.Name = st.Name;

                    sm.RollNo = st.Rollno;

                    sm.Address = st.Address;

                    sm.Class = st.Class;

                    DB.studentmasters.Add(sm);

                    DB.SaveChanges();

                    return new Response

                    {

                        Status = "Success",

                        Message = "Data Successfully"

                    };

                }

                else

                {

                    var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();

                    if (obj.Id > 0)

                    {


                        obj.Name = st.Name;

                        obj.RollNo = st.Rollno;

                        obj.Address = st.Address;

                        obj.Class = st.Class;

                        DB.SaveChanges();

                        return new Response

                        {

                            Status = "Updated",

                            Message = "Updated Successfully"

                        };

                    }

                }

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            return new Response

            {

                Status = "Error",

                Message = "Data not insert"

            };


        }

        [Route("Studentdetails")]

        [HttpGet]

        public object Studentdetails()

        {


            var a = DB.studentmasters.ToList();

            return a;

        }


        [Route("StudentdetailById")]

        [HttpGet]

        public object StudentdetailById(int id)

        {

            var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();

            return obj;

        }

        [Route("Deletestudent")]

        [HttpDelete]

        public object Deletestudent(int id)

        {

            var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();

            DB.studentmasters.Remove(obj);

            DB.SaveChanges();

            return new Response

            {

                Status = "Delete",

                Message = "Delete Successfuly"

            };

        }

    }

}



Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines:

  EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");

  config.EnableCors(cors);


Create React.js Project

To create a new ReactJS project, open the command prompt, and enter the following command:

npx create-react-app crudwithceactjs  

Open the newly created project in Visual Studio Code and install Reactstrap and Bootstrap by using the following commands:

npm install --save bootstrap  

npm install --save reactstrap react react-dom  

Now, go to the "src" folder and add a new folder "Student" and four new components:

Addstudent.js

Studentlist.js

Editstudent.js

Table.js 



Install the Axios library by using the following command. Learn more about Axios library

npm install --save axios  

Add routing: Use the following command to add routing in React.

npm install react-router-dom --save  

Now, open the Addstudent.js file and add the following code:

import React from 'react';  
import axios from 'axios';  
import '../Student/Addstudent.css' ;
import { Container, Col, Form, Row, FormGroup, Label, Input, Button }
from 'reactstrap';  
class Addstudent extends React.Component{  
    constructor(props){  
        super(props)  
        this.state = {  
            Name:'',  
            RollNo:'',  
            Class:'',  
            Address:''  
        }  
    }  
    Addstudent=()=>{  
        axios.post('http://localhost:52564/Api/Student/AddotrUpdatestudent/',
{Name:this.state.Name,RollNo:this.state.RollNo,  
            Class:this.state.Class, Address:this.state.Address})  
      .then(json => {  
          if(json.data.Status==='Success'){  
              console.log(json.data.Status);  
              alert("Data Save Successfully");  
              this.props.history.push('/Studentlist')  
          }  
          else{  
              alert('Data not Saved');
              this.props.history.push('/Studentlist')  
          }  
      })  
    }  
   
        handleChange= (e)=> {  
            this.setState({[e.target.name]:e.target.value});  
        }  
   
render() {  
return (  
<Container className="App">  
<h4 className="PageHeading">Enter Student Informations</h4>  
<Form className="form">  
<Col>  
<FormGroup row>  
<Label for="name" sm={2}>Name</Label>  
<Col sm={10}>  
<Input type="text" name="Name" onChange={this.handleChange}
value={this.state.Name} placeholder="Enter Name" />  
</Col>  
</FormGroup>  
<FormGroup row>  
<Label for="address" sm={2}>RollNo</Label>  
<Col sm={10}>  
<Input type="text" name="RollNo" onChange={this.handleChange}
value={this.state.RollNo} placeholder="Enter RollNo" />  
</Col>  
</FormGroup>  
<FormGroup row>  
<Label for="Password" sm={2}>Class</Label>  
<Col sm={10}>  
<Input type="text" name="Class" onChange={this.handleChange}
value={this.state.Class} placeholder="Enter Class" />  
</Col>  
</FormGroup>  
<FormGroup row>  
<Label for="Password" sm={2}>Address</Label>  
<Col sm={10}>  
<Input type="text" name="Address" onChange={this.handleChange}
value={this.state.Address} placeholder="Enter Address" />  
</Col>  
</FormGroup>  
</Col>  
<Col>  
<FormGroup row>  
<Col sm={5}>  
</Col>  
<Col sm={1}>  
<button type="button" onClick={this.Addstudent}
className="btn btn-success">Submit</button>  
</Col>  
<Col sm={1}>  
<Button color="danger">Cancel</Button>{' '}  
</Col>  
<Col sm={5}>  
</Col>  
</FormGroup>  
</Col>  
</Form>  
</Container>  
);  
}  
   
}     
export default Addstudent;   


Add a new file  Addstudet.css file and add the following CSS classes. Import this file in the  Addstudent.js component.

.PageHeading    {    

  margin-top: 10px;    

  margin-bottom: 10px;    

  color :black !important;    

}   


Now, add a Table.js file and add the following code:

import React, { Component } from 'react';  
import axios from 'axios';  
import { Link } from 'react-router-dom';  
class Table extends Component {  
    constructor(props) {  
        super(props);  
    }  
     
    DeleteStudent= () =>{  
        axios.delete('http://localhost:52564/Api/Student/Deletestudent?id='+
        this.props.obj.Id)  
       .then(json => {  
           if(json.data.Status==='Delete'){  
               alert('Record deleted successfully!!');  
           }  
       })  
    }  
        render() {  
            return (  
                <tr>  
                  <td>  
                    {this.props.obj.Name}  
                  </td>  
                  <td>  
                    {this.props.obj.RollNo}  
                  </td>  
                  <td>  
                    {this.props.obj.Class}  
                  </td>  
                  <td>  
                    {this.props.obj.Address}  
                  </td>  
                  <td>  
                  <Link to={"/edit/"+this.props.obj.Id}
                    className="btn btn-success">Edit</Link>  
                  </td>  
                  <td>  
                    <button type="button" onClick={this.DeleteStudent}
                        className="btn btn-danger">Delete</button>  
                  </td>  
                </tr>  
    );  
    }  
}  
 
export default Table;  

Now, add a studentlist.js file and add the following code.

import React, { Component } from 'react';  
import axios from 'axios';  
import Table from './Table';  
 
export default class Studentlist extends Component {  
 
    constructor(props) {  
        super(props);  
        this.state = {business: []};  
    }  
    componentDidMount(){  
        debugger;  
        axios.get('http://localhost:52564/Api/Student/Studentdetails')  
          .then(response => {  
              this.setState({ business: response.data });  
              debugger;  
 
          })  
          .catch(function (error) {  
              console.log(error);  
          })  
    }  
     
    tabRow(){  
        return this.state.business.map(function(object, i){  
            return <Table obj={object} key={i} />;  
        });  
    }  
 
    render() {  
        return (  
          <div>  
            <h4 align="center">Student List</h4>  
            <table className="table table-striped" style={{ marginTop: 10 }}>  
              <thead>  
                <tr>  
                  <th>Name</th>  
                  <th>RollNo</th>  
                  <th>Class</th>  
                  <th>Address</th>  
                  <th colSpan="4">Action</th>  
                </tr>  
              </thead>  
              <tbody>  
               { this.tabRow() }  
              </tbody>  
            </table>  
          </div>  
      );  
}  
}

Add EditStudent.js file with the following code:

import React from 'react';  
import { Container, Col, Form, Row, FormGroup, Label, Input, Button } from 'reactstrap';  
import axios from 'axios'  
import '../Student/Addstudent.css'  
class Edit extends React.Component {  
    constructor(props) {  
        super(props)  
     
        this.onChangeName = this.onChangeName.bind(this);  
        this.onChangeRollNo = this.onChangeRollNo.bind(this);  
        this.onChangeClass = this.onChangeClass.bind(this);  
        this.onChangeAddress = this.onChangeAddress.bind(this);  
        this.onSubmit = this.onSubmit.bind(this);  
 
        this.state = {  
            Name: '',  
            RollNo: '',  
            Class: '',  
            Address: ''  
 
        }  
    }  
 
    componentDidMount() {  
        axios.get('http://localhost:52564/Api/Student/StudentdetailById?id='+this.props.match.params.id)  
            .then(response => {  
                this.setState({  
                    Name: response.data.Name,  
                    RollNo: response.data.RollNo,  
                    Class: response.data.Class,  
                    Address: response.data.Address });  
 
            })  
            .catch(function (error) {  
                console.log(error);  
            })  
    }  
 
    onChangeName(e) {  
        this.setState({  
            Name: e.target.value  
        });  
    }  
    onChangeRollNo(e) {  
        this.setState({  
            RollNo: e.target.value  
        });    
    }  
    onChangeClass(e) {  
        this.setState({  
            Class: e.target.value  
        });  
    }  
    onChangeAddress(e) {  
        this.setState({  
            Address: e.target.value  
        });  
    }  
 
    onSubmit(e) {  
        e.preventDefault();  
        const obj = {  
            Id:this.props.match.params.id,  
            Name: this.state.Name,  
            RollNo: this.state.RollNo,  
            Class: this.state.Class,  
            Address: this.state.Address  
 
        };  
        axios.post('http://localhost:52564/Api/Student/AddotrUpdatestudent/', obj)  
            .then(res => console.log(res.data));  
        this.props.history.push('/Studentlist')  
    }  
    render() {  
        return (  
            <Container className="App">  
 
             <h4 className="PageHeading">Update Student Informations</h4>  
                <Form className="form" onSubmit={this.onSubmit}>  
                    <Col>  
                        <FormGroup row>  
                            <Label for="name" sm={2}>Name</Label>  
                            <Col sm={10}>  
                                <Input type="text" name="Name"
            value={this.state.Name} onChange={this.onChangeName}  
    placeholder="Enter Name" />  
</Col>  
</FormGroup>  
<FormGroup row>  
    <Label for="Password" sm={2}>RollNo</Label>  
    <Col sm={10}>  
        <Input type="text" name="RollNo" value={this.state.RollNo}
           onChange={this.onChangeRollNo} placeholder="Enter RollNo" />  
    </Col>  
</FormGroup>  
 <FormGroup row>  
    <Label for="Password" sm={2}>Class</Label>  
    <Col sm={10}>  
        <Input type="text" name="Class" value={this.state.Class}
        onChange={this.onChangeClass} placeholder="Enter Class" />  
    </Col>  
</FormGroup>  
 <FormGroup row>  
    <Label for="Password" sm={2}>Address</Label>  
    <Col sm={10}>  
        <Input type="text" name="Address"value={this.state.Address}
        onChange={this.onChangeAddress} placeholder="Enter Address" />  
    </Col>  
</FormGroup>  
</Col>  
<Col>  
<FormGroup row>  
    <Col sm={5}>  
    </Col>  
    <Col sm={1}>  
  <Button type="submit" color="success">Submit</Button>{' '}  
    </Col>  
    <Col sm={1}>  
        <Button color="danger">Cancel</Button>{' '}  
    </Col>  
    <Col sm={5}>  
    </Col>  
</FormGroup>  
</Col>  
</Form>  
</Container>  
);  
    }  
 
    }  
 
export default Edit;  

Open the App.js file with the following code in it.

import React from 'react';  
import Addstudent from './components/Student/Addstudent';  
import Studentlist from './components/Student/Studentlist';  
import EditStudent from './components/Student/EditStudent';  
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
import './App.css';  
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {  
  return (  
    <Router>  
      <div className="container">  
        <nav className="navbar navbar-expand-lg navheader">  
          <div className="collapse navbar-collapse" >  
            <ul className="navbar-nav mr-auto">  
              <li className="nav-item">  
                <Link to={'/Addstudent'} className="nav-link">Addstudent</Link>  
              </li>  
              <li className="nav-item">  
                <Link to={'/Studentlist'} className="nav-link">Student List</Link>  
              </li>  
            </ul>  
          </div>  
        </nav> <br />  
        <Switch>  
          <Route exact path='/Addstudent' component={Addstudent} />  
          <Route path='/edit/:id' component={EditStudent} />  
          <Route path='/Studentlist' component={Studentlist} />  
        </Switch>  
      </div>  
    </Router>  
  );  
}  

export default App;

Add the following CSS classes in the App.css file.

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

Now, run the application by using the  npm start command and check the result.



Click on the Add Student button to add a new record into the database.



Click on the Edit button to update a record.



Click on the Delete button to delete a record.




Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...