Monday 25 October 2021

CRUD Operations Using Web API And ReactJS

 In this article, I'm going to perform CRUD operations using Web API and React.js. ReactJS is an open-source JavaScript library that is used for creating user interfaces. It is developed and maintained by Facebook. Learn more about React.

 
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
Step 1 - 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". 
  1. USE [CrudDemo]  
  2. GO  
  3. CREATE TABLE [dbo].[studentmaster](  
  4.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  5.     [Name] [varchar](50) NULL,  
  6.     [RollNo] [varchar](50) NULL,  
  7.     [Class] [varchar](50) NULL,  
  8.     [Address] [varchar](50) NULL,  
  9.  CONSTRAINT [PK_studentmaster] PRIMARY KEY CLUSTERED   
  10. (  
  11.     [Id] ASC  
  12. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  13. ) ON [PRIMARY]  
  14.   
  15. GO  

Create a new Web API project

 
Step 2
 
Open Visual Studio and create a new project. 
 
CRUD Operations Using Web API And ReactJS
 
Step 3
 
Change the name to CrudUsingReact.
 
CRUD Operations Using Web API And ReactJS
 
Step 4
 
Choose the template as Web API.
 
CRUD Operations Using Web API And ReactJS
 
Step 5
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
CRUD Operations Using Web API And ReactJS
 
Step 6
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
CRUD Operations Using Web API And ReactJS
 
Step 7
 
Select EF Designer from the database and click the "Next" button.
 
CRUD Operations Using Web API And ReactJS
 
Step 8
 
Add the connection properties and select database name on the next page and click OK.
 
CRUD Operations Using Web API And ReactJS
 
Step 9
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
CRUD Operations Using Web API And ReactJS
 
Step 10
 
Right-click on Models folder and add two classes - Student and Response respectively. Now, paste the following codes in these classes.
  1. public class Student  
  2.    {  
  3.        public string Name { get; set; }  
  4.        public string Rollno { get; set; }  
  5.        public string Class { get; set; }  
  6.        public string Address { get; set; }  
  7.    }  
  1. public class Response  
  2.    {  
  3.        public string Status { get; set; }  
  4.        public string Message { get; set; }  
  5.    }  
Step 11
 
Right-click on the Controllers folder and add a new controller. Name it as "Student controller" and add the following namespace in the Student controller.
  1. using CrudUsingReact.Models;  
Step 12
 
Now, add a method to insert and update data into the database.
  1. [Route("AddotrUpdatestudent")]  
  2.        [HttpPost]  
  3.        public object AddotrUpdatestudent(Student st)  
  4.        {  
  5.            try  
  6.            {  
  7.                if (st.Id == 0)  
  8.                {  
  9.                    studentmaster sm = new studentmaster();  
  10.                    sm.Name = st.Name;  
  11.                    sm.RollNo = st.Rollno;  
  12.                    sm.Address = st.Address;  
  13.                    sm.Class = st.Class;  
  14.                    DB.studentmasters.Add(sm);  
  15.                    DB.SaveChanges();  
  16.                    return new Response  
  17.                    {  
  18.                        Status = "Success",  
  19.                        Message = "Data Successfully"  
  20.                    };  
  21.                }  
  22.                else  
  23.                {  
  24.                    var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();  
  25.                    if (obj.Id > 0)  
  26.                    {  
  27.                       
  28.                        obj.Name = st.Name;  
  29.                        obj.RollNo = st.Rollno;  
  30.                        obj.Address = st.Address;  
  31.                        obj.Class = st.Class;  
  32.                        DB.SaveChanges();  
  33.                        return new Response  
  34.                        {  
  35.                            Status = "Updated",  
  36.                            Message = "Updated Successfully"  
  37.                        };  
  38.                    }  
  39.                }  
  40.            }  
  41.            catch (Exception ex)  
  42.            {  
  43.                Console.Write(ex.Message);  
  44.            }  
  45.            return new Response  
  46.            {  
  47.                Status = "Error",  
  48.                Message = "Data not insert"  
  49.            };  
  50.   
  51.        }  
Step 13
 
Add other methods to delete and fetch data respectively from the database.
  1. [Route("Deletestudent")]  
  2.       [HttpDelete]  
  3.       public object Deletestudent(int id)  
  4.       {  
  5.           var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
  6.           DB.studentmasters.Remove(obj);  
  7.           DB.SaveChanges();  
  8.           return new Response  
  9.           {  
  10.               Status = "Delete",  
  11.               Message = "Delete Successfuly"  
  12.           };  
  13.       }  
  1. [HttpGet]  
  2.       public object   Studentdetails()  
  3.       {  
  4.            
  5.               var a = DB.studentmasters.ToList();  
  6.               return a;  
  7.       }  
Complete Student controller code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using CrudUsingReact.Models;  
  8.   
  9. namespace CrudUsingReact.Controllers  
  10. {  
  11.     [RoutePrefix("Api/Student")]  
  12.     public class studentController : ApiController  
  13.     {  
  14.         CrudDemoEntities DB = new CrudDemoEntities();  
  15.         [Route("AddotrUpdatestudent")]  
  16.         [HttpPost]  
  17.         public object AddotrUpdatestudent(Student st)  
  18.         {  
  19.             try  
  20.             {  
  21.                 if (st.Id == 0)  
  22.                 {  
  23.                     studentmaster sm = new studentmaster();  
  24.                     sm.Name = st.Name;  
  25.                     sm.RollNo = st.RollNo;  
  26.                     sm.Address = st.Address;  
  27.                     sm.Class = st.Class;  
  28.                     DB.studentmasters.Add(sm);  
  29.                     DB.SaveChanges();  
  30.                     return new Response  
  31.                     {  
  32.                         Status = "Success",  
  33.                         Message = "Data Successfully"  
  34.                     };  
  35.                 }  
  36.                 else  
  37.                 {  
  38.                     var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();  
  39.                     if (obj.Id > 0)  
  40.                     {  
  41.                        
  42.                         obj.Name = st.Name;  
  43.                         obj.RollNo = st.RollNo;  
  44.                         obj.Address = st.Address;  
  45.                         obj.Class = st.Class;  
  46.                         DB.SaveChanges();  
  47.                         return new Response  
  48.                         {  
  49.                             Status = "Updated",  
  50.                             Message = "Updated Successfully"  
  51.                         };  
  52.                     }  
  53.                 }  
  54.             }  
  55.             catch (Exception ex)  
  56.             {  
  57.                 Console.Write(ex.Message);  
  58.             }  
  59.             return new Response  
  60.             {  
  61.                 Status = "Error",  
  62.                 Message = "Data not insert"  
  63.             };  
  64.   
  65.         }  
  66.         [Route("Studentdetails")]  
  67.         [HttpGet]  
  68.         public object   Studentdetails()  
  69.         {  
  70.              
  71.                 var a = DB.studentmasters.ToList();  
  72.                 return a;  
  73.         }  
  74.   
  75.         [Route("StudentdetailById")]  
  76.         [HttpGet]  
  77.         public object StudentdetailById(int id)  
  78.         {  
  79.             var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
  80.             return obj;  
  81.         }  
  82.         [Route("Deletestudent")]  
  83.         [HttpDelete]  
  84.         public object Deletestudent(int id)  
  85.         {  
  86.             var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
  87.             DB.studentmasters.Remove(obj);  
  88.             DB.SaveChanges();  
  89.             return new Response  
  90.             {  
  91.                 Status = "Delete",  
  92.                 Message = "Delete Successfuly"  
  93.             };  
  94.         }  
  95.     }  
  96. }  
Step 14
 
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.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");    
  2. config.EnableCors(cors);   

Create React.js Project

 
Step 15
 
To create a new ReactJS project, open the command prompt and enter the following command.
  1. npx create-react-app crudwithceactjs  
Open the newly created project in Visual Studio Code and install Reactstrap and Bootstrap in this project by using the following commands respectively.
  1. npm install --save bootstrap  
  2. npm install --save reactstrap react react-dom  
Step 16
 
Now, go to the "src" folder and add a new folder "Student" and add 4 new components.
  1. Addstudent.js
  2. Studentlist.js
  3. Editstudent.js
  4. Table.js 
CRUD Operations Using Web API And ReactJS
 
Step 17
 
Install the Axios library by using the following command. Learn more about Axios library
  1. npm install --save axios   
Step 18
 
Add routing: Use the following command to add routing in React.
  1. npm install react-router-dom --save    
Step 19
 
Now, open the Addstudent.js file and add following code.
  1. import React from 'react';  
  2. import axios from 'axios';  
  3. import '../Student/Addstudent.css'  
  4. import { Container, Col, Form, Row, FormGroup, Label, Input, Button } from 'reactstrap';  
  5. class Addstudent extends React.Component{  
  6. constructor(props){  
  7. super(props)  
  8. this.state = {  
  9. Name:'',  
  10. RollNo:'',  
  11. Class:'',  
  12. Address:''  
  13. }  
  14. }   
  15. Addstudent=()=>{  
  16.   axios.post('http://localhost:52564/Api/Student/AddotrUpdatestudent/', {Name:this.state.Name,RollNo:this.state.RollNo,  
  17.   Class:this.state.Class, Address:this.state.Address})  
  18. .then(json => {  
  19. if(json.data.Status==='Success'){  
  20.   console.log(json.data.Status);  
  21.   alert("Data Save Successfully");  
  22. this.props.history.push('/Studentlist')  
  23. }  
  24. else{  
  25. alert('Data not Saved');  
  26. debugger;  
  27. this.props.history.push('/Studentlist')  
  28. }  
  29. })  
  30. }  
  31.    
  32. handleChange= (e)=> {  
  33. this.setState({[e.target.name]:e.target.value});  
  34. }  
  35.    
  36. render() {  
  37. return (  
  38.    <Container className="App">  
  39.     <h4 className="PageHeading">Enter Student Informations</h4>  
  40.     <Form className="form">  
  41.       <Col>  
  42.         <FormGroup row>  
  43.           <Label for="name" sm={2}>Name</Label>  
  44.           <Col sm={10}>  
  45.             <Input type="text" name="Name" onChange={this.handleChange} value={this.state.Name} placeholder="Enter Name" />  
  46.           </Col>  
  47.         </FormGroup>  
  48.         <FormGroup row>  
  49.           <Label for="address" sm={2}>RollNo</Label>  
  50.           <Col sm={10}>  
  51.             <Input type="text" name="RollNo" onChange={this.handleChange} value={this.state.RollNo} placeholder="Enter RollNo" />  
  52.           </Col>  
  53.         </FormGroup>  
  54.         <FormGroup row>  
  55.           <Label for="Password" sm={2}>Class</Label>  
  56.           <Col sm={10}>  
  57.             <Input type="text" name="Class" onChange={this.handleChange} value={this.state.Class} placeholder="Enter Class" />  
  58.           </Col>  
  59.         </FormGroup>  
  60.         <FormGroup row>  
  61.           <Label for="Password" sm={2}>Address</Label>  
  62.           <Col sm={10}>  
  63.             <Input type="text" name="Address" onChange={this.handleChange} value={this.state.Address} placeholder="Enter Address" />  
  64.           </Col>  
  65.         </FormGroup>  
  66.       </Col>  
  67.       <Col>  
  68.         <FormGroup row>  
  69.           <Col sm={5}>  
  70.           </Col>  
  71.           <Col sm={1}>  
  72.           <button type="button" onClick={this.Addstudent} className="btn btn-success">Submit</button>  
  73.           </Col>  
  74.           <Col sm={1}>  
  75.             <Button color="danger">Cancel</Button>{' '}  
  76.           </Col>  
  77.           <Col sm={5}>  
  78.           </Col>  
  79.         </FormGroup>  
  80.       </Col>  
  81.     </Form>  
  82.   </Container>  
  83. );  
  84. }  
  85.    
  86. }  
  87.    
  88. export default Addstudent;  
  89.    
Add a new file Addstudet.css file and add the following CSS classes. Import this file in Addstudent.js component.
  1. .PageHeading    
  2. {    
  3.   margin-top: 10px;    
  4.   margin-bottom: 10px;    
  5.   color :black !important;    
  6. }    
Step 20
 
Now, add a Table.js file and add the following code.
  1. import React, { Component } from 'react';  
  2. import axios from 'axios';  
  3. import { Link } from 'react-router-dom';  
  4. class Table extends Component {  
  5.   constructor(props) {  
  6.     super(props);  
  7.     }  
  8.       
  9.     DeleteStudent= () =>{  
  10.      axios.delete('http://localhost:52564/Api/Student/Deletestudent?id='+this.props.obj.Id)  
  11.     .then(json => {  
  12.     if(json.data.Status==='Delete'){  
  13.     alert('Record deleted successfully!!');  
  14.     }  
  15.     })  
  16.     }  
  17.   render() {  
  18.     return (  
  19.         <tr>  
  20.           <td>  
  21.             {this.props.obj.Name}  
  22.           </td>  
  23.           <td>  
  24.             {this.props.obj.RollNo}  
  25.           </td>  
  26.           <td>  
  27.             {this.props.obj.Class}  
  28.           </td>  
  29.           <td>  
  30.             {this.props.obj.Address}  
  31.           </td>  
  32.           <td>  
  33.           <Link to={"/edit/"+this.props.obj.Id} className="btn btn-success">Edit</Link>  
  34.           </td>  
  35.           <td>  
  36.             <button type="button" onClick={this.DeleteStudent} className="btn btn-danger">Delete</button>  
  37.           </td>  
  38.         </tr>  
  39.     );  
  40.   }  
  41. }  
  42.   
  43. export default Table;  
Step 21
 
Now, add a studentlist.js file and add the following code.
  1. import React, { Component } from 'react';  
  2. import axios from 'axios';  
  3. import Table from './Table';  
  4.   
  5. export default class Studentlist extends Component {  
  6.   
  7.   constructor(props) {  
  8.       super(props);  
  9.       this.state = {business: []};  
  10.     }  
  11.     componentDidMount(){  
  12.       debugger;  
  13.       axios.get('http://localhost:52564/Api/Student/Studentdetails')  
  14.         .then(response => {  
  15.           this.setState({ business: response.data });  
  16.           debugger;  
  17.   
  18.         })  
  19.         .catch(function (error) {  
  20.           console.log(error);  
  21.         })  
  22.     }  
  23.       
  24.     tabRow(){  
  25.       return this.state.business.map(function(object, i){  
  26.           return <Table obj={object} key={i} />;  
  27.       });  
  28.     }  
  29.   
  30.     render() {  
  31.       return (  
  32.         <div>  
  33.           <h4 align="center">Student List</h4>  
  34.           <table className="table table-striped" style={{ marginTop: 10 }}>  
  35.             <thead>  
  36.               <tr>  
  37.                 <th>Name</th>  
  38.                 <th>RollNo</th>  
  39.                 <th>Class</th>  
  40.                 <th>Address</th>  
  41.                 <th colSpan="4">Action</th>  
  42.               </tr>  
  43.             </thead>  
  44.             <tbody>  
  45.              { this.tabRow() }   
  46.             </tbody>  
  47.           </table>  
  48.         </div>  
  49.       );  
  50.     }  
  51.   }  
Step 22
 
Add EditStudent.js file with the following code.
  1. import React from 'react';   
  2. import { Container, Col, Form, Row, FormGroup, Label, Input, Button } from 'reactstrap';  
  3. import axios from 'axios'  
  4. import '../Student/Addstudent.css'  
  5. class Edit extends React.Component {  
  6.     constructor(props) {  
  7.         super(props)  
  8.      
  9.     this.onChangeName = this.onChangeName.bind(this);  
  10.     this.onChangeRollNo = this.onChangeRollNo.bind(this);  
  11.     this.onChangeClass = this.onChangeClass.bind(this);  
  12.     this.onChangeAddress = this.onChangeAddress.bind(this);  
  13.     this.onSubmit = this.onSubmit.bind(this);  
  14.   
  15.          this.state = {  
  16.             Name: '',  
  17.             RollNo: '',  
  18.             Class: '',  
  19.             Address: ''  
  20.   
  21.         }  
  22.     }  
  23.   
  24.   componentDidMount() {  
  25.       axios.get('http://localhost:52564/Api/Student/StudentdetailById?id='+this.props.match.params.id)  
  26.           .then(response => {  
  27.               this.setState({   
  28.                 Name: response.data.Name,   
  29.                 RollNo: response.data.RollNo,  
  30.                 Class: response.data.Class,  
  31.                 Address: response.data.Address });  
  32.   
  33.           })  
  34.           .catch(function (error) {  
  35.               console.log(error);  
  36.           })  
  37.     }  
  38.   
  39.   onChangeName(e) {  
  40.     this.setState({  
  41.         Name: e.target.value  
  42.     });  
  43.   }  
  44.   onChangeRollNo(e) {  
  45.     this.setState({  
  46.         RollNo: e.target.value  
  47.     });    
  48.   }  
  49.   onChangeClass(e) {  
  50.     this.setState({  
  51.         Class: e.target.value  
  52.     });  
  53. }  
  54.     onChangeAddress(e) {  
  55.         this.setState({  
  56.             Address: e.target.value  
  57.         });  
  58.   }  
  59.   
  60.   onSubmit(e) {  
  61.     debugger;  
  62.     e.preventDefault();  
  63.     const obj = {  
  64.         Id:this.props.match.params.id,  
  65.       Name: this.state.Name,  
  66.       RollNo: this.state.RollNo,  
  67.       Class: this.state.Class,  
  68.       Address: this.state.Address  
  69.   
  70.     };  
  71.     axios.post('http://localhost:52564/Api/Student/AddotrUpdatestudent/', obj)  
  72.         .then(res => console.log(res.data));  
  73.         debugger;  
  74.         this.props.history.push('/Studentlist')  
  75.   }  
  76.     render() {  
  77.         return (  
  78.             <Container className="App">  
  79.   
  80.              <h4 className="PageHeading">Update Student Informations</h4>  
  81.                 <Form className="form" onSubmit={this.onSubmit}>  
  82.                     <Col>  
  83.                         <FormGroup row>  
  84.                             <Label for="name" sm={2}>Name</Label>  
  85.                             <Col sm={10}>  
  86.                                 <Input type="text" name="Name" value={this.state.Name} onChange={this.onChangeName}  
  87.                                 placeholder="Enter Name" />  
  88.                             </Col>  
  89.                         </FormGroup>  
  90.                         <FormGroup row>  
  91.                             <Label for="Password" sm={2}>RollNo</Label>  
  92.                             <Col sm={10}>  
  93.                                 <Input type="text" name="RollNo" value={this.state.RollNo} onChange={this.onChangeRollNo} placeholder="Enter RollNo" />  
  94.                             </Col>  
  95.                         </FormGroup>  
  96.                          <FormGroup row>  
  97.                             <Label for="Password" sm={2}>Class</Label>  
  98.                             <Col sm={10}>  
  99.                                 <Input type="text" name="Class" value={this.state.Class} onChange={this.onChangeClass} placeholder="Enter Class" />  
  100.                             </Col>  
  101.                         </FormGroup>  
  102.                          <FormGroup row>  
  103.                             <Label for="Password" sm={2}>Address</Label>  
  104.                             <Col sm={10}>  
  105.                                 <Input type="text" name="Address"value={this.state.Address} onChange={this.onChangeAddress} placeholder="Enter Address" />  
  106.                             </Col>  
  107.                         </FormGroup>   
  108.                     </Col>  
  109.                     <Col>  
  110.                         <FormGroup row>  
  111.                             <Col sm={5}>  
  112.                             </Col>  
  113.                             <Col sm={1}>  
  114.                           <Button type="submit" color="success">Submit</Button>{' '}  
  115.                             </Col>  
  116.                             <Col sm={1}>  
  117.                                 <Button color="danger">Cancel</Button>{' '}  
  118.                             </Col>  
  119.                             <Col sm={5}>  
  120.                             </Col>  
  121.                         </FormGroup>  
  122.                     </Col>  
  123.                 </Form>  
  124.             </Container>  
  125.         );  
  126.     }  
  127.   
  128. }  
  129.   
  130. export default Edit;  
Step 23
 
Open the App.js file having the following code in it.
  1. import React from 'react';  
  2. import Addstudent from './Student/Addstudent';  
  3. import Studentlist from './Student/Studentlist';  
  4. import EditStudent from './Student/EditStudent';  
  5. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
  6. import './App.css';  
  7. function App() {  
  8.   return (  
  9.     <Router>  
  10.       <div className="container">  
  11.         <nav className="navbar navbar-expand-lg navheader">  
  12.           <div className="collapse navbar-collapse" >  
  13.             <ul className="navbar-nav mr-auto">  
  14.               <li className="nav-item">  
  15.                 <Link to={'/Addstudent'} className="nav-link">Addstudent</Link>  
  16.               </li>  
  17.               <li className="nav-item">  
  18.                 <Link to={'/Studentlist'} className="nav-link">Student List</Link>  
  19.               </li>  
  20.             </ul>  
  21.           </div>  
  22.         </nav> <br />  
  23.         <Switch>  
  24.           <Route exact path='/Addstudent' component={Addstudent} />  
  25.           <Route path='/edit/:id' component={EditStudent} />  
  26.           <Route path='/Studentlist' component={Studentlist} />  
  27.         </Switch>  
  28.       </div>  
  29.     </Router>  
  30.   );  
  31. }  
  32.   
  33. export default App;  
Add the following CSS classes in App.css file.
  1. .App {    
  2.   text-align: center;    
  3. }    
  4. .navheader{    
  5.   margin-top: 10px;    
  6.   color :black !important;    
  7.   background-color: #b3beca!important    
  8. }    
Now, run the application by using 'npm start' command and check the result .

CRUD Operations Using Web API And ReactJS

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

CRUD Operations Using Web API And ReactJS

Click on the Edit button to update a record.
 
CRUD Operations Using Web API And ReactJS

Click on Delete button to delete a record.
 
CRUD Operations Using Web API And ReactJS
 

Summary

 
In this article, we learned how to perform CRUD operations using React, Web API, and SQL Server. In the next article, we will learn how we can create a login and registration page using react and Web API.

No comments:

Post a Comment