DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Virtual Reality and Augmented Reality in the Browser
  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)

Trending

  • LLM-Powered Deep Parsing for Industrial Inventory Search
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • How to Write for DZone Publications: Trend Reports and Refcards
  • Compliance Automated Standard Solution (COMPASS), Part 11: Compliance as Code, the OSCAL MCP Server Way
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Search Records Between Two Dates Using Web API and ReactJS

How to Search Records Between Two Dates Using Web API and ReactJS

By 
Sanwar Ranwa user avatar
Sanwar Ranwa
DZone Core CORE ·
Apr. 14, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

Searching records between two dates is very simple. In this article, we will see how we can perform this using a stored procedure with 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 a React.js Project

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

Shell
xxxxxxxxxx
1
 
1
npx create-react-app searchrecord 


Open the newly created project in Visual Studio Code and add Bootstrap to it by using the following command.

Shell
xxxxxxxxxx
1
 
1
npm install --save bootstrap 


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

JavaScript
xxxxxxxxxx
1
 
1
import 'bootstrap/dist/css/bootstrap.min.css';    

 
Now, install the react-datepicker library in this project by using the following command:

Shell
xxxxxxxxxx
1
 
1
npm install react-datepicker --save    


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

Shell
xxxxxxxxxx
1
 
1
npm install --save axios    


Now, go to the src folder and create a new component, Searchdata.js and add the following code to the component:

JavaScript
xxxxxxxxxx
1
101
 
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 a reference to the component in the app.js file:

JavaScript
xxxxxxxxxx
1
13
 
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

SQL
xxxxxxxxxx
1
15
 
1
CREATE TABLE [dbo].[Employee](      
2
    [Id] [int] NOT NULL,      
3
    [Name] [varchar](50) NULL,      
4
    [City] [varchar](50) NULL,      
5
    [JoiningDate] [date] NULL,      
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 = ON) ON [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:

SQL
xxxxxxxxxx
1
 
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. 

Creating a new project

Change the name to Searchdata and click ok. 

Changing project name

Select Web API as the template. 

Selecting Web API as template

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

Adding new item

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

Adding ADO.NET Entity Data Model

Select EF Designer from the database and click the Next button:  

Selecting EF Designer

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

Connecting to database

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

Checking Table and stored procedures checkbox

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:

C#
xxxxxxxxxx
1
 
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 "Searchdata controller" and add the following namespace in the Searchdata controller.  

C#
xxxxxxxxxx
1
 
1
using Searchdata.Models;   


Now, add two methods to fetch data and search data by dates from the database.

C#
xxxxxxxxxx
1
30
 
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:

C#
xxxxxxxxxx
1
 
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 date pickers and click on the search button.

Web API Database

Opinions expressed by DZone contributors are their own.

Related

  • Virtual Reality and Augmented Reality in the Browser
  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook