How to Search Records Between Two Dates Using Web API and ReactJS
Join the DZone community and get the full member experience.
Join For FreeSearching 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:
xxxxxxxxxx
npx create-react-app searchrecord
Open the newly created project in Visual Studio Code and add Bootstrap to it by using the following command.
xxxxxxxxxx
npm install --save bootstrap
Now, open the index.js file and add the Bootstrap reference.
xxxxxxxxxx
import 'bootstrap/dist/css/bootstrap.min.css';
Now, install the react-datepicker
library in this project by using the following command:
xxxxxxxxxx
npm install react-datepicker --save
Install Axios by using the following command. Learn more about Axios library.
xxxxxxxxxx
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:
xxxxxxxxxx
import React, { Component } from 'react'
import './App.css';
import axios from "axios";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
export class Searchdata extends Component {
constructor(props) {
super(props)
this.state = {
employeedata: [],
startdate: '' ,
enddate:''
}
}
Changedate = (e) => {
this.setState({
startdate: e
});
};
enddate = (e) => {
this.setState({
enddate: e
});
};
componentDidMount() {
axios.get('http://localhost:1141/Api/Searchdata/showdata').then(response => {
console.log(response.data);
this.setState({
employeedata: response.data
});
});
}
onsubmit = (e) => {
debugger;
const data = { startdate:this.state.startdate, enddate:this.state.enddate};
e.preventDefault();
axios.post('http://localhost:1141/Api/Searchdata/search',data).then(response => {
console.log(response.data);
this.setState({
employeedata: response.data
});
});
}
render() {
return (
<div>
<div className="row">
<div className="col-sm-12 btn btn-info">
How to Search Data Between Two Dates Using Web API and ReactJS
</div>
</div>
<form onSubmit={this.onsubmit}>
<div className="row hdr" >
<div className="col-sm-3 form-group"> </div>
<div className="col-sm-3 form-group">
<DatePicker className="form-control"
selected={this.state.startdate} placeholderText="Select Date" showPopperArrow={false}
onChange={this.Changedate}
/>
</div>
<div className="col-sm-3 form-group">
<DatePicker className="form-control"
selected={this.state.enddate} placeholderText="Select Date" showPopperArrow={false}
onChange={this.enddate}
/>
</div>
<div className="col-sm-3 form-group">
<button type="submit" className="btn btn-success" >Search</button>
</div>
</div>
</form>
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">City</th>
<th scope="col">JoiningDate</th>
</tr>
</thead>
<tbody>
{
this.state.employeedata.map((p, index) => {
return <tr key={index}>
<th scope="row">{p.Id}</th>
<td>{p.Name}</td>
<td>{p.City}</td>
<td>{p.JoiningDate }</td>
</tr>
})
}
</tbody>
</table>
</div>
)
}
}
export default Searchdata
Add a reference to the component in the app.js file:
xxxxxxxxxx
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Searchdata from "./Searchdata";
function App() {
return (
<div className="App">
<Searchdata></Searchdata>
</div>
);
}
export default App;
Create a Table in the Database
xxxxxxxxxx
CREATE TABLE [dbo].[Employee](
[Id] [int] NOT NULL,
[Name] [varchar](50) NULL,
[City] [varchar](50) NULL,
[JoiningDate] [date] NULL,
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
SET ANSI_PADDING OFF
GO
Create a stored procedure to find the data between two dates:
xxxxxxxxxx
CREATE PROC [dbo].[Usp_Empsearch]
@Fromdate DATETIME,@Todate DATETIME
AS
BEGIN
SELECT * FROM Employee WHERE JoiningDate BETWEEN @Fromdate AND @Todate
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 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 the 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:
xxxxxxxxxx
public class searchdata
{
public DateTime startdate { get; set; }
public DateTime enddate { get; set; }
}
Right-click on the Controllers folder and add a new controller. Name it "Searchdata controller" and add the following namespace in the Searchdata controller.
xxxxxxxxxx
using Searchdata.Models;
Now, add two methods to fetch data and search data by dates from the database.
xxxxxxxxxx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Searchdata.Models;
namespace Searchdata.Controllers
{
[RoutePrefix("Api/Searchdata")]
public class SearchdataController : ApiController
{
employeesEntities DB = new employeesEntities();
[Route("showdata")]
[HttpGet]
public object showdata()
{
var a = DB.Employees.ToList();
return a;
}
[Route("search")]
[HttpPost]
public object search(searchdata sd)
{
var a= DB.Usp_Empsearch(sd.startdate, sd.enddate);
return a;
}
}
}
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:
xxxxxxxxxx
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
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.
Opinions expressed by DZone contributors are their own.
Comments