Search Records Between Two Dates Using Stored Procedure, Web API And ReactJS

Searching records between two dates is very simple. In here, we will see how we can perform this using a stored procedure ,Web API and ReactJS.
 
Prerequisites
  • Basic Knowledge of ReactJS 
  • Visual Studio Code
  • Visual studio and SQL Server Management studio
  • Node and NPM installed
  • Bootstrap
  • React-datepicker

Create React.js Project

 
To create a new ReactJS project, open the command prompt and enter the following command.
  1. npx create-react-app searchrecord  
Open the newly created project in Visual Studio Code and Bootstrap in this project by using the following command. 
  1. npm install --save bootstrap    
Now, open the index.js file and add Bootstrap reference.
  1. import 'bootstrap/dist/css/bootstrap.min.css';    
 Now install 'react-datepicker' library in this project by using the following command.
  1. npm install react-datepicker --save    
Install the Axios library by using the following command. Learn more about Axios library 
  1. npm install --save axios     
Now go to src folder and create a new component 'Searchdata.js' and add the following code in this component. 
  1. import React, { Component } from 'react'  
  2. import './App.css';  
  3. import axios from "axios";  
  4. import DatePicker from "react-datepicker";    
  5. import "react-datepicker/dist/react-datepicker.css";    
  6. export class Searchdata extends Component {  
  7.     constructor(props) {  
  8.         super(props)  
  9.   
  10.         this.state = {  
  11.             employeedata: [],  
  12.             startdate: '' ,  
  13.             enddate:''   
  14.         }  
  15.     }  
  16.     Changedate = (e) => {    
  17.         this.setState({    
  18.                 startdate: e    
  19.         });    
  20. };  
  21. enddate = (e) => {    
  22.     this.setState({    
  23.         enddate: e    
  24.     });    
  25. };  
  26.     componentDidMount() {  
  27.         axios.get('http://localhost:1141/Api/Searchdata/showdata').then(response => {  
  28.             console.log(response.data);  
  29.             this.setState({  
  30.                 employeedata: response.data  
  31.             });  
  32.         });  
  33.     }  
  34.     onsubmit = (e) => {    
  35.         debugger;  
  36.         const data = { startdate:this.state.startdate, enddate:this.state.enddate};    
  37.         e.preventDefault();    
  38.         axios.post('http://localhost:1141/Api/Searchdata/search',data).then(response => {  
  39.             console.log(response.data);  
  40.             this.setState({  
  41.                 employeedata: response.data  
  42.             });  
  43.         });  
  44. }     
  45.     render() {  
  46.         return (  
  47.             <div>  
  48.                 <div className="row">  
  49.                     <div className="col-sm-12 btn btn-info">  
  50.                         How to  Search Data Between Two Dates Using Web API and ReactJS  
  51.                  </div>  
  52.                 </div>  
  53.                 <form onSubmit={this.onsubmit}>  
  54.                     <div className="row hdr" >  
  55.                         <div className="col-sm-3 form-group">  </div>  
  56.                         <div className="col-sm-3 form-group">  
  57.                                 <DatePicker className="form-control"    
  58.                                                         selected={this.state.startdate} placeholderText="Select Date" showPopperArrow={false}    
  59.                                                         onChange={this.Changedate}    
  60.                                                 />    
  61.                         </div>  
  62.                         <div className="col-sm-3 form-group">  
  63.                                  <DatePicker className="form-control"    
  64.                                                         selected={this.state.enddate} placeholderText="Select Date" showPopperArrow={false}    
  65.                                                         onChange={this.enddate}    
  66.                                                 />    
  67.                         </div>  
  68.                         <div className="col-sm-3 form-group">  
  69.                             <button type="submit" className="btn btn-success" >Search</button>  
  70.                         </div>  
  71.                     </div>  
  72.                 </form>  
  73.                 <table className="table">  
  74.                     <thead className="thead-dark">  
  75.                         <tr>  
  76.                             <th scope="col">Id</th>  
  77.                             <th scope="col">Name</th>  
  78.                             <th scope="col">City</th>  
  79.                             <th scope="col">JoiningDate</th>  
  80.                         </tr>  
  81.                     </thead>  
  82.                     <tbody>  
  83.                         {  
  84.                     this.state.employeedata.map((p, index) => {  
  85.                       return  <tr key={index}>  
  86.                             <th scope="row">{p.Id}</th>  
  87.                             <td>{p.Name}</td>  
  88.                             <td>{p.City}</td>  
  89.                     <td>{p.JoiningDate }</td>  
  90.                         </tr>  
  91.                     })   
  92.                     }  
  93.                     </tbody>  
  94.                 </table>  
  95.   
  96.             </div>  
  97.         )  
  98.     }  
  99. }  
  100.   
  101. export default Searchdata  
Add reference of this component in app.js file,
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Searchdata from "./Searchdata";  
  5. function App() {  
  6.   return (  
  7.     <div className="App">  
  8.       <Searchdata></Searchdata>  
  9.     </div>  
  10.   );  
  11. }  
  12.   
  13. export default App;  
Create a Table in the Database
  1. CREATE TABLE [dbo].[Employee](        
  2.     [Id] [intNOT NULL,        
  3.     [Name] [varchar](50) NULL,        
  4.     [City] [varchar](50) NULL,        
  5.     [JoiningDate] [dateNULL,        
  6. PRIMARY KEY CLUSTERED         
  7. (        
  8.     [Id] ASC        
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]        
  10. ON [PRIMARY]        
  11.         
  12. GO        
  13.         
  14. SET ANSI_PADDING OFF        
  15. GO     
Create a stored procedure to find the data between two dates. 
  1. CREATE PROC [dbo].[Usp_Empsearch]        
  2. @Fromdate DATETIME,@Todate DATETIME        
  3. AS        
  4. BEGIN        
  5. SELECT * FROM Employee WHERE JoiningDate BETWEEN @Fromdate AND @Todate        
  6. END       

Create a New Web API Project

 
Open Visual Studio and create a new project.
 
 
Change the Name to Searchdata and Click ok.
 
 
Select Web API as its 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" and "stored procedures" checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
 
Our data model is successfully created now.
 
Right-click on the Models folder and add a class searchdata. Now, paste the following code in this class.
  1. public class searchdata    
  2.     {    
  3.         public DateTime startdate { get; set; }    
  4.         public DateTime enddate { get; set; }    
  5.     }   
Right-click on the Controllers folder and add a new controller. Name it as "Searchdata controller" and add the following namespace in the Searchdata controller.
  1. using Searchdata.Models;    
Now, add two methods to fetch data and search data by dates from the database.
  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 Searchdata.Models;    
  8. namespace Searchdata.Controllers    
  9. {    
  10.     [RoutePrefix("Api/Searchdata")]    
  11.     public class SearchdataController : ApiController    
  12.     {    
  13.         employeesEntities DB = new employeesEntities();    
  14.         [Route("showdata")]    
  15.         [HttpGet]    
  16.         public object showdata()    
  17.        {    
  18.             var a = DB.Employees.ToList();    
  19.             return a;    
  20.         }    
  21.     
  22.         [Route("search")]    
  23.         [HttpPost]    
  24.         public object search(searchdata sd)    
  25.         {    
  26.             var a= DB.Usp_Empsearch(sd.startdate, sd.enddate);    
  27.             return a;    
  28.         }    
  29.     }    
  30. }    
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);    
 Now, go to Visual Studio code and run the project by using the following command: 'npm start'
 
 
 Now select dates from the datepickers and click on search button
 
 

Summary


In this article, we learned how to search records between two dates using Web API and ReactJS.