The main aim to write this article is, there are lot of articles and samples related to MVC and AngularJS but there are not much articles and examples related to ReactJS and MVC and also there is no proper article that are samples which explain how to display data from SQL Server data base to MVC page using ReactJS and WCF Rest Service. I planned to explain the following using a simple program:
In this article we will see in detail the following:
- Create first ReactJS using simple HTML page to display hello message.
- Create ReactJS using simple HTML page to display Data.
- Create ReactJS using MVC and WEB API to display JSON data from Controller to view.
- Create ReactJS using MVC and WCF Rest Service to display the data from database result to bind in MVC page using ReactJS and WCF Rest Service.
What is ReactJS?
ReactJS is an open source JavaScript library developed by Facebook team and maintained by Facebook and Instagram. ReactJS has only View Part which is nothing but a UI part. In MVC it has (Model View and Controller) and in ReactJS it has only View part. ReactJS can be used when dealing with large data which will be frequently changed. The ReactJS script file will be saved as an extension of JSX.
To understand more details about ReactJS kindly check the following reference links.
1. ReactJS and our first program
2. Create ReactJS using simple HTML page to display data
Hope now you have some basic understanding of ReactJS, for more kindly refer to the reference links given above. Now let’s see how to declare a variable and display the variable data in ReactJS.
Code Part
So for we have seen a sample program using html and ReactJS. Now we will see how to use ReactJS in MVC.
Prerequisites
Visual Studio 2015. You can download it from
here.
3. Simple MVC, ReactJS and Web API to display JSON from controller to MVC View using React JS
Create our MVC web application in Visual Studio 2015. After installing Visual Studio 2015, click Start, then Programs and click Visual Studio 2015.
Click New -> Project and select
Web, then
ASP.NET Web Application. Select your project location and enter the web application name.
Select
MVC and under
Add Folders and Core reference for, select the Web API and click OK.
Once our MVC application created, the next step is to add
ReactJS to our application.
Home Controller
In your home controller add the following method to return the JSON result. Here I am returning ItemName and price. We need to give the URL as
/Home/GetMessage to get the result in our ReactJS script.
- public JsonResult GetItemDetails()
- {
- return Json(new { ItemName = "Samsung Notebook / ",Price=" 1500 RS " }, JsonRequestBehavior.AllowGet);
- }
Installing ReactJS package
If the ReactJS package is missing then add the package to your project.
Right-click your MVC project and click Manage NuGet Packages. Search for ReactJS, then select ReactJS tools for ASP.NET MVC 4 and 5 and click Install.
Creating our JSX file
Add JSX script file to Scripts folder.
Right Click Scripts folder and Click
Add, then select
New Item.
Select
Web, then JavaScript File. After that enter script file name with “
JSX” extension, for example "
shanuWebAPISample.jsx” and click
Add.
Now we can see our JSX file has been created.Here we can add our ReactJS script.
Here is the complete code of our JSX which will display the data result to MVC View.
- var App = React.createClass({
-
- getInitialState: function() {
- return {
- data: []
- };
- },
-
- componentWillMount: function() {
- var xhr = new XMLHttpRequest();
- xhr.open('get', this.props.url, true);
- xhr.onload = function() {
- var webAPIData = JSON.parse(xhr.responseText);
-
- this.setState({
- data: webAPIData
- });
- }.bind(this);
- xhr.send();
- },
-
- render: function() {
- return (
-
- < h2 > {
- this.state.data
- } < /h2>
- );
- }
- });
-
- React.render( < App url = "/Home/GetItemDetails" / > , document.getElementById('reactContent'));
Code part Explanation: - React.render(<App url="/Home/GetItemDetails" />, document.getElementById('reactContent'));
In
React.render here first we pass our WEB API url (our controller and Method name ) to get the result. The final result has been bind to the DOM.
In our custom Component we create a Class and get the JSON result data by passing the URL and final result has been rendered displayed to our Div tag by using the
>{this.state.data.
- var App = React.createClass({
-
- getInitialState: function() {
- return {
- data: []
- };
- },
-
- componentWillMount: function() {
- var xhr = new XMLHttpRequest();
- xhr.open('get', this.props.url, true);
- xhr.onload = function() {
- var webAPIData = JSON.parse(xhr.responseText);
-
- this.setState({
- data: webAPIData
- });
- }.bind(this);
- xhr.send();
- },
-
- render: function() {
- return (
-
- < h2 > {
- this.state.data
- } < /h2>
- );
- }
- });
In View add the script file references and the div tag to display our result.
- <html>
-
- <head>
- <title>Hello React</title>
- </head>
-
- <body>
-
- <table width="99%" style=" border-bottom:3px solid #3273d5;">
- <tr>
- <td class="style1" align="center">
- <h2>Shanu - Welcome to my first ReactJs with MVC and WEB API :)</h2>
- </td>
- </tr>
- <tr>
- <td></td>
- </tr>
- </table>
-
- <table style='width: 99%;table-layout:fixed;'>
- <tr>
- <td>
- <table style=" background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2" cellspacing="2">
- <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
- <td align="center">
- <h3> Here is our WEB API Json result from ReactJS</h3>
- </td>
- <tr style="height: 30px; background-color:#d1d6dc ; color:#FFFFFF ;border: solid 1px #659EC7;">
- <td align="center">
- <div id="reactContent" style="color:red"></div>
-
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
-
-
- <br />
- <script src="http://fb.me/react-0.13.1.js"></script>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery-1.10.2.js"></script>
- <script src="~/Scripts/shanuWebAPISample.jsx"></script>
- </body>
-
- </html>
When we run the program we can see the following output.
4. Create ReactJS using MVC and WCF Rest Service to display the data from the database result to bind in MVC page using ReactJS and WCF Rest Service
Now let’s see in detail how to create a WCF REST Service using Entity Framework 6 to get the data from our SQL Server database and bind the result to MVC view using ReactJS.
First we create a sample database and table to display result from the database to MVC page using ReactJS and WCF REST.
Create Database and Table
Script to create database, table and sample insert data:
- USE MASTER
- GO
-
-
- for the Database Exists.If the database is exist then drop and create new DB
- IF EXISTS(SELECT[name] FROM sys.databases WHERE[name] = 'ItemDB')
- DROP DATABASE ItemDB
- GO
-
- CREATE DATABASE ItemDB
- GO
-
- USE ItemDB
- GO
-
-
-
- IF EXISTS(SELECT[name] FROM sys.tables WHERE[name] = 'ItemDetail')
- DROP TABLE ItemDetail
- GO
-
- CREATE TABLE[dbo].[ItemDetail](
- [ItemID] INT IDENTITY PRIMARY KEY, [ItemName][varchar](100) NOT NULL, [Desc][varchar](100) NOT NULL, [Price][varchar](20) NOT NULL
- )
-
-
- INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])
- VALUES('NoteBook', 'HP Notebook 15 Inch', '24500')
-
- INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])
- VALUES('MONITOR', 'SAMSNG', '8500')
-
- INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])
- VALUES('MOBILE', 'SAMSUNG NOTE 5', '59500')
-
- INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])
- VALUES('MOUSE', 'ABKO', '780')
-
- INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])
- VALUES('HDD', 'LG', '3780')
-
- Select * from ItemDetail
After creating our database and table, let’s create our WCF Rest Application first.
Create WCF REST Service
Create our MVC web application in Visual Studio 2015. After installing our Visual Studio 2015, click Start, then go to
Programs and click Visual Studio 2015.
Open Visual Studio 2015, select
File,
New and click
Project, then select WCF Service Application then select your project path and name your WCF service and click OK.
Once we have created our WCF Service we can see “IService.CS” and “Service1.svc” in the Solution Explorer as in the following.
In
IService.CS create our
DataContract and
OperationContract method to get the data. Here is the code to add in DataContract and OperationContract method to get the data.
- public interface IService1 {
-
- [OperationContract]
- [WebInvoke(Method = "GET",
- RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json,
- UriTemplate = "/GetItemDetails/")]
- List < ShanuDataContract.itemDetailsDataContract > GetItemDetails();
-
-
- }
-
- public class ShanuDataContract {
- [DataContract]
- public class itemDetailsDataContract {
- [DataMember]
- public string ItemID {
- get;
- set;
- }
-
- [DataMember]
- public string ItemName {
- get;
- set;
- }
-
- [DataMember]
- public string Desc {
- get;
- set;
- }
-
- [DataMember]
- public string Price {
- get;
- set;
- }
-
-
- }
- }
Add Database using ADO.NET Entity Data Model
Right-click your
WCF project and select
Add New Item, then
ADO.NET Entity Data Model and click
Add.
Select EF Designer from the Database and click "
Next".
Click "
New Connection".
Here we can select our Database Server Name and enter DB server SQL Server Authentication User ID and Password. We have already created our database “
ItemDB”, so we can select the database and click OK.
Click Next and select tables that need to be used. In our example we need to use “
ItemDB " and “
ItemDetail”. Select both the tables and click "
Finish".
Here we can see that now we have created our
ItemDataModel.
Service1.SVC
“
Service.SVC.CS” implements the
IService Interface and overrides and defines all the methods of the Operation Contract.
For example, here we can see I have implemented the
IService1 in the
Service1 class. Created the object for our Entity model and in
GetItemDetails using a LINQ Query I have selected the data from the
ItemDetails table and the result was added to the list.
- public class Service1: IService1 {
- ItemDBEntities OME;
- public Service1() {
- OME = new ItemDBEntities();
- }
-
- public List < ShanuDataContract.itemDetailsDataContract > GetItemDetails() {
- var query = (from a in OME.ItemDetails select a).Distinct();
-
- List < ShanuDataContract.itemDetailsDataContract > ItemDetailsList = new List < ShanuDataContract.itemDetailsDataContract > ();
-
- query.ToList().ForEach(rec => {
- ItemDetailsList.Add(new ShanuDataContract.itemDetailsDataContract {
- ItemID = Convert.ToString(rec.ItemID),
- ItemName = rec.ItemName,
- Desc = rec.Desc,
- Price = rec.Price
- });
- });
- return ItemDetailsList;
- }
- }
Web.Config
In the WCF project's “Web.Config”, make the following changes:
- Change <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />.
2. Replace the </behaviors> to:
- <endpointBehaviors>
- <behavior>
- <webHttp helpEnabled="True" />
- </behavior>
- </endpointBehaviors>
- </behaviors>
Run WCF Service
Now we have created our WCF Rest service, let's run and test our service. Here we can see the result.
So now we have completed our WCF and now it's time to create our MVC ReactJS application.
We can add a new project to our existing project and create a new MVC web application as in the following.
Click New -> Project then select Web -> ASP.NET Web Application. Select your project location and enter your web application name.
Select MVC and in Add folders and core reference for. Select the Web API and click OK.
Once our MVC application created, the next step is to add ReactJS to our application.
Installing ReactJS package
If the ReactJS package is missing then add the package to your project.
Right-click your MVC project and click Manage NuGet Packages. Search for ReactJS - > Select ReactJS tools for ASP.NET MVC 4 and 5 and click Install.
Creating our JSX file
Add JSX script file to Scripts folder.
Right click Scripts folder and Click Add -> New Item.
Select Web -> Select JavaScript File -> Enter script file name with “JSX” extension for example like “shanuWebAPISample.jsx” and click ADD.
Now we can see our JSX file has been created. Here we can add our ReactJS script.
Here is the complete code of our JSX which will display the data result to MVC View.
- var ItemDetailList = React.createClass({
- render: function() {
-
- var itemTable = this.props.data.map(function(itemarray) {
-
- return (
-
- < ItemArray >
-
- < table >
- < tr >
- < td width = "40" > < /td> < td width = "140"
- align = "center" > {
- itemarray.ItemID
- } < /td> < td width = "240"
- align = "center" > {
- itemarray.ItemName
- } < /td> < td width = "120"
- align = "right" > {
- itemarray.Price
- } < /td> < td width = "420"
- align = "center" > {
- itemarray.Desc
- } < /td> < td > < /td> < /tr> < /table>
-
-
- < /ItemArray>
-
- );
- });
- return ( < div > {
- itemTable
- } < /div>);
- }
- });
-
- var ItemArray = React.createClass({
- render: function() {
- return ( < div > {
- this.props.children
- } < /div>);
- }
- });
-
- var ItemContainer = React.createClass({
-
- getInitialState: function() {
- return {
- data: []
- };
- },
-
- componentWillMount: function() {
- var xhr = new XMLHttpRequest();
- xhr.open('get', this.props.url, true);
- xhr.onload = function() {
- var itemData = JSON.parse(xhr.responseText);
-
- this.setState({
- data: itemData
- });
- }.bind(this);
- xhr.send();
- },
-
- render: function() {
- return (
-
- < ItemDetailList data = {
- this.state.data
- }
- />
- );
- }
- });
-
- React.render( < ItemContainer url = "http://localhost:39290/Service1.svc/getItemDetails/" / > , document.getElementById('reactContent'));
Code part Explanation
In the above WEB API sample I have explained about how to pass the URL and bind the result Div tag by binding it to DOM. Here I have used the same method but passed the URL as my WCF URL “
http://localhost:39290/Service1.svc/getItemDetails/”. Here I got the result and displayed the data in tabular form inside the div tag.
When we run the program we can see the following output.
Note: In my attached Zip file you can find all the four source samples: two for HTML sample and one for MVC and Web ApI, one for MVC and WCF Rest using ReactJS. Hope you liked this article and if you have any questions, then kindly mention it in the comments section.
Thank You!