Display Data In Grid Using Web API 2 And ReactJS

Introduction

 
In this post, we will see how to bind data in a grid by using the ReactJS library, ASP.Net Web API 2, and Entity Framework ORM.
 
In this demo, we are going create a sample application, then generate a mapping of our employee table by using Entity Framework, after that, we will create a service which returns all data from employee table. Finally, ReactJS as a library will be used in order to bind data in a grid.
 
Let’s start.
 
SQL Database part
 
Here, you will find the scripts to create a database and table.
 
Create Database 
  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object:  Database [DbEmployee]    Script Date: 3/26/2017 6:19:33 AM ******/  
  5. CREATE DATABASE [DbEmployee]  
  6.  CONTAINMENT = NONE  
  7.  ON  PRIMARY   
  8. NAME = N'DbEmployee', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbEmployee.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9.  LOG ON   
  10. NAME = N'DbEmployee_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbEmployee_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [DbEmployee] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [DbEmployee].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [DbEmployee] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [DbEmployee] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [DbEmployee] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [DbEmployee] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [DbEmployee] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [DbEmployee] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [DbEmployee] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [DbEmployee] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [DbEmployee] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [DbEmployee] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [DbEmployee] SET CURSOR_DEFAULT  GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [DbEmployee] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [DbEmployee] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [DbEmployee] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [DbEmployee] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [DbEmployee] SET  DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [DbEmployee] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [DbEmployee] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [DbEmployee] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [DbEmployee] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [DbEmployee] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [DbEmployee] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [DbEmployee] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [DbEmployee] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [DbEmployee] SET  MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [DbEmployee] SET PAGE_VERIFY CHECKSUM    
  98. GO  
  99.   
  100. ALTER DATABASE [DbEmployee] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [DbEmployee] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [DbEmployee] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [DbEmployee] SET  READ_WRITE   
  110. GO   
Create Table 
  1. USE [DbEmployee]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[EmployeeTable]    Script Date: 3/26/2017 6:20:03 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[EmployeeTable](  
  15.     [EmployeeID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [FirstName] [varchar](50) NULL,  
  17.     [LastName] [varchar](50) NULL,  
  18.     [Gender] [varchar](50) NULL,  
  19.     [Designation] [nchar](10) NULL,  
  20.     [Salary] [intNULL,  
  21.     [City] [varchar](50) NULL,  
  22.     [Country] [varchar](50) NULL,  
  23.  CONSTRAINT [PK_EmployeeTable] PRIMARY KEY CLUSTERED   
  24. (  
  25.     [EmployeeID] ASC  
  26. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  27. ON [PRIMARY]  
  28.   
  29. GO  
  30.   
  31. SET ANSI_PADDING OFF  
  32. GO   
After creating the table, you can add some records as shown below.
 
React
 
Create your Web API application
 
Open Visual Studio and select File >> New Project.
 
The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.
 
ASP.NET Web Application
 
The next step is to select a template. In this example, we need to choose the Web API template and click the Ok button.
 
Web API template
 
After creating our project, it’s time to add ADO.NET Entity Data Model. Let’s Go.
 
Adding ADO.NET Entity Data Model
 
For adding ADO.NET Entity Framework. Right-click on the project name, click Add > Add New Item. A dialog box will pop up, inside Visual C# select Data then ADO.NET Entity Data Model, and enter a name for your Dbcontext model as DbEmployee, finally click Add.
 
ADO.NET Entity Data Model
 
Now, we are going to choose EF Designer from the database as shown below.
 
Entity Data Model Wizard
 
After clicking the Next button, a dialog will pop up with the name connection properties. You need to enter your server name and connect to a database panel, selecting the database via dropdown List (DB Employee), then click OK button.
 
Entity Data Model Wizard
 
In the final step, the dialog Entity Data Model Wizard will pop up for choosing an object which we want to use. In our case, we are going to choose the Employee table and click the Finish button. Finally, we see that the EDMX model generates an EmployeeTable class.
 
EDMX model
 
Create a controller
 
Now, we are going to create a controller. Right-click on the controllers folder > Add > Controller> selecting Web API 2 Controller – Empty > click Add.
 
Web API 2 Controller
 
Enter Controller name (‘EmployeeController’).
 
Web API 2 Controller
 
EmployeeController.cs 
  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.   
  8. namespace DisplayDataReactJS.Controllers  
  9. {  
  10.     [RoutePrefix("api/Employee")]  
  11.     public class EmployeeController : ApiController  
  12.     {  
  13.         //Db Context  
  14.         DbEmployeeEntities db = new DbEmployeeEntities();  
  15.   
  16.         [Route("GetEmployeeList")]  
  17.         public IQueryable<EmployeeTable> GetEmployeeList()  
  18.         {  
  19.             return db.EmployeeTables.AsQueryable();  
  20.         }  
  21.   
  22.     }  
  23. }   
As you can see, I am creating GetEmployeeList() action to select all data from the employee table in JSON format.
 
ReactJS part
 
Before all this, we are installing the ReactJS library. For this, open package manager console and running the following commands:
 
PM> install-package react.js
 
install-package react.js
 
PM> install-package React.Web.Mvc4
 
install-package React.Web.Mvc4
 
In order to create new jsx file. Right click on Scripts folder > Add > JavaScript File.
 
create jsx file
 
EmployeeJSX.jsx 
  1. var EmployeeRow = React.createClass({  
  2.   
  3.       render: function () {  
  4.           return(  
  5.               <tr>  
  6.                   <td>{this.props.item.EmployeeID}</td>  
  7.                   <td>{this.props.item.FirstName}</td>  
  8.                   <td>{this.props.item.LastName}</td>  
  9.                   <td>{this.props.item.Gender}</td>  
  10.                   <td>{this.props.item.Designation}</td>  
  11.                   <td>{this.props.item.Salary}</td>  
  12.                   <td>{this.props.item.City}</td>  
  13.                   <td>{this.props.item.Country}</td>  
  14.               </tr>  
  15.   
  16.               );  
  17.       }  
  18.   });  
  19.   
  20.   var EmployeeTable = React.createClass({  
  21.           
  22.       getInitialState: function(){  
  23.           
  24.           return{  
  25.               result:[]  
  26.           }  
  27.       },  
  28.       componentWillMount: function(){  
  29.   
  30.           var xhr = new XMLHttpRequest();  
  31.           xhr.open('get'this.props.url, true);  
  32.           xhr.onload = function () {  
  33.               var response = JSON.parse(xhr.responseText);  
  34.   
  35.               this.setState({ result: response });  
  36.   
  37.           }.bind(this);  
  38.           xhr.send();  
  39.       },  
  40.       render: function(){  
  41.           var rows = [];  
  42.           this.state.result.forEach(function (item) {  
  43.               rows.push(<EmployeeRow  key={item.EmployeeID} item={item}/>);  
  44.       });  
  45.   return (<table className="table">  
  46.      <thead>  
  47.          <tr>  
  48.             <th>EmployeeID</th>  
  49.             <th>FirstName</th>  
  50.             <th>LastName</th>  
  51.             <th>Gender</th>  
  52.             <th>Designation</th>  
  53.             <th>Salary</th>  
  54.             <th>City</th>  
  55.             <th>Country</th>  
  56.          </tr>  
  57.      </thead>  
  58.   
  59.       <tbody>  
  60.           {rows}  
  61.       </tbody>  
  62.   
  63.   </table>);  
  64.   }  
  65.       
  66.   });  
  67.   
  68.   ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList"/>,   
  69.           document.getElementById('grid'))   
Create HTML Page
 
To add HTML Page. Right click on project name > Add > HTML Page.
 
React
 
EmployeeGrid.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>.: Employee Grid :.</title>  
  5.     <meta charset="utf-8" />  
  6. </head>  
  7. <body>  
  8.     <h3>Employee List - Web API 2 & ReactJS </h3>  
  9.   
  10.     <div id="grid" class="container">  
  11.   
  12.     </div>  
  13.   
  14.     <!--CSS-->  
  15.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  16.     <!-- JS -->  
  17.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  18.   
  19.     <script src="Scripts/react/react.js"></script>  
  20.     <script src="Scripts/react/react-dom.js"></script>  
  21.   
  22.     <script src="Scripts/EmployeeJSX.jsx"></script>  
  23.   
  24.   
  25.       
  26. </body>  
  27. </html>   
Note
 
Don’t forget to add the following libraries in your HTML page. 
  1. <!--CSS-->  
  2.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  3.   
  4.   
  5.     <!-- JS -->  
  6.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  7.   
  8.     <script src="Scripts/react/react.js"></script>  
  9.     <script src="Scripts/react/react-dom.js"></script>  
  10.   
  11.     <script src="Scripts/EmployeeJSX.jsx"></script>   
Output
 
Now build your application and you can see the following output.
 
Web API 2 ReactJS
 
Happy Coding.