MVC Using ReactJS And WCF Rest For Beginners

MVC using ReactJS

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:

  1. Create first ReactJS using simple HTML page to display hello message.
  2. Create ReactJS using simple HTML page to display Data.
  3. Create ReactJS using MVC and WEB API to display JSON data from Controller to view.
  4. 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

    Step 1: Add the ReactJS JS link to run our ReactJS html page.

    1. <script src="https://fb.me/react-0.13.3.js"></script>  
    2. <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>  
    Step 2: In your html body tag declare div tag and give proper id (name) for the div tag.

    From ReactJS we will display all the result to this div tag.
    1. <div id="myName"></div>  
    Step 3: Create our first ReactJS script. Here we will add the type as ="text/jsx".
    1. <script type="text/jsx">  
    Step 4: renderComponent – In ReactJS we can see many components, here render component is to render the result and bind to the DOM (which is our div tag). In the following sample we bind the NameDisplay component to DOM.
    1. React.render(  
    2.    <NameDisplay />,  
    3.    document.getElementById('myName')  
    4. );  
    Step 5: createClass- We can create our own custom component by using React.createClass. In the following example I have created a custom component NameDisplay. In this Component I will return the DIV with our message as “my Name is Shanu, Welcome to ReactJS”.

    We bind this component to DOM.
    1. var NameDisplay = React.createClass({  
    2.     render: function() {  
    3.         return ( < div >  
    4.             my Name is Shanu, Welcome to ReactJS. < /div>  
    5.         );  
    6.     }  
    7. });  
    Here is the complete HTML source code, when we run the following code in browser we see the following output:

    see the output
    Save the following code as html and open in browser: “shanuFirstReactJS.html”. 
    1. <!DOCTYPE html>  
    2. <html>  
    3.   
    4. <head>  
    5.     <meta charset="UTF-8" />  
    6.     <title>Welcome to ReactJs</title>  
    7.     <script src="https://fb.me/react-0.13.3.js"></script>  
    8.     <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>  
    9. </head>  
    10.   
    11. <body>  
    12.     <div id="myName"></div>  
    13.     <script type="text/jsx">  
    14.   
    15.         var NameDisplay = React.createClass({ render: function() { return (  
    16.         <div>  
    17.             my Name is Shanu,Welcome to ReactJS.  
    18.         </div>  
    19.         ); } }); React.render(  
    20.         <NameDisplay />, document.getElementById('myName') );  
    21.     </script>  
    22. </body>  
    23.   
    24. </html>   

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.

    Step 1: Declare a variable and add the sample data like the following:

    1. var data = [{  
    2.     Count: 1,  
    3.     Author: "Shanu",  
    4.     Bookdesc: "C# Book written by Shanu ",  
    5.     NAMES: "C#"  
    6. }, {  
    7.     Count: 2,  
    8.     Author: "Afreen",  
    9.     Bookdesc: "C# Book written by Shanu ",  
    10.     NAMES: "REACTJS"  
    11. }, {  
    12.     Count: 3,  
    13.     Author: "Afraz",  
    14.     Bookdesc: "ASP.NET MVC Book written by Shanu ",  
    15.     NAMES: "ASP.NET MVC"  
    16. }];  
    Step 2: Same like above code we create our own Custom Component using React.createClass, this time in the main component I have passed the result data to another component named BooksList.
    1. var BooksContainer = React.createClass({  
    2.     render: function() {  
    3.         return ( < div className = "commentBox" >  
    4.             < h1 > Book Details < /h1>  < BooksList data = {  
    5.                 this.props.data  
    6.             }  
    7.             />  < /div>  
    8.         );  
    9.     }  
    10. });  
    Step 3: In BooksList component I displayed the data one by one from the bookArray component.

    Save the following code as html and open in browser: “BookDetailsReactJs.html”.

    BookDetailsReactJs
    1. <!DOCTYPE html>  
    2. <html>  
    3.   
    4. <head>  
    5.     <meta charset="UTF-8" />  
    6.     <title>Shanu ReactJs</title>  
    7.     <script src="https://fb.me/react-0.13.3.js"></script>  
    8.     <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>  
    9. </head>  
    10.   
    11. <body>  
    12.     <div id="bookContainer"></div>  
    13.     <script type="text/jsx">  
    14.   
    15.         var data = [ { Count : 1, Author: "Shanu", Bookdesc: "C# Book written by Shanu " , NAMES: "C#"}, { Count : 2, Author: "Afreen", Bookdesc: "C# Book written by Shanu " , NAMES: "REACTJS"}, { Count : 3, Author: "Afraz", Bookdesc: "ASP.NET MVC Book written by Shanu ", NAMES: "ASP.NET MVC" } ]; var BooksList = React.createClass({ render: function() { var bookDetails = this.props.data.map(function (book) { return (  
    16.         <bookArray>  
    17.             <b>No. </b> {book.Count}  
    18.             <b> Author : </b> {book.Author}  
    19.             <b> Book Desc : </b> {book.Bookdesc}  
    20.             <b> Author Name : </b> {book.NAMES}  
    21.             <br />  
    22.         </bookArray>  
    23.         ); }); return (  
    24.         <div>  
    25.             {bookDetails}  
    26.         </div>  
    27.         ); } }); var bookArray = React.createClass({ render: function() { return (  
    28.         <div>  
    29.             {this.props.children}  
    30.         </div>  
    31.         ); } }); var BooksContainer = React.createClass({ render: function() { return (  
    32.         <div className="commentBox">  
    33.             <h1>Book Details</h1>  
    34.   
    35.             <BooksList data={this.props.data} />  
    36.   
    37.         </div>  
    38.         ); } }); React.render(  
    39.         <BooksContainer data={data} />, document.getElementById('bookContainer') );  
    40.   
    41.     </script>  
    42. </body>  
    43.   
    44. </html>   
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.

enter your web application name

Select MVC and under Add Folders and Core reference for, select the Web API and click OK.

Select MVC

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.
  1. public JsonResult GetItemDetails()  
  2. {  
  3.    return Json(new { ItemName = "Samsung Notebook / ",Price=" 1500 RS " }, JsonRequestBehavior.AllowGet);  
  4. }  
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.

NuGet Packages

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.

JavaScript File

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.
  1. var App = React.createClass({  
  2.   
  3.     getInitialState: function() {  
  4.         return {  
  5.             data: []  
  6.         };  
  7.     },  
  8.   
  9.     componentWillMount: function() {  
  10.         var xhr = new XMLHttpRequest();  
  11.         xhr.open('get'this.props.url, true);  
  12.         xhr.onload = function() {  
  13.             var webAPIData = JSON.parse(xhr.responseText);  
  14.   
  15.             this.setState({  
  16.                 data: webAPIData  
  17.             });  
  18.         }.bind(this);  
  19.         xhr.send();  
  20.     },  
  21.   
  22.     render: function() {  
  23.         return (  
  24.   
  25.             < h2 > {  
  26.                 this.state.data  
  27.             } < /h2>  
  28.         );  
  29.     }  
  30. });  
  31.   
  32. React.render( < App url = "/Home/GetItemDetails" / > , document.getElementById('reactContent'));  
Code part Explanation:
  1. 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.
  1. var App = React.createClass({  
  2.   
  3.     getInitialState: function() {  
  4.         return {  
  5.             data: []  
  6.         };  
  7.     },  
  8.   
  9.     componentWillMount: function() {  
  10.         var xhr = new XMLHttpRequest();  
  11.         xhr.open('get'this.props.url, true);  
  12.         xhr.onload = function() {  
  13.             var webAPIData = JSON.parse(xhr.responseText);  
  14.   
  15.             this.setState({  
  16.                 data: webAPIData  
  17.             });  
  18.         }.bind(this);  
  19.         xhr.send();  
  20.     },  
  21.   
  22.     render: function() {  
  23.         return (  
  24.   
  25.             < h2 > {  
  26.                 this.state.data  
  27.             } < /h2>  
  28.         );  
  29.     }  
  30. });  
In View add the script file references and the div tag to display our result.
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Hello React</title>  
  5. </head>  
  6.   
  7. <body>  
  8.   
  9.     <table width="99%" style=" border-bottom:3px solid #3273d5;">  
  10.         <tr>  
  11.             <td class="style1" align="center">  
  12.                 <h2>Shanu - Welcome to my first ReactJs with MVC and WEB API :)</h2>  
  13.             </td>  
  14.         </tr>  
  15.         <tr>  
  16.             <td></td>  
  17.         </tr>  
  18.     </table>  
  19.   
  20.     <table style='width: 99%;table-layout:fixed;'>  
  21.         <tr>  
  22.             <td>  
  23.                 <table style=" background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2" cellspacing="2">  
  24.                     <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  25.                         <td align="center">  
  26.                             <h3> Here is our WEB API Json result from ReactJS</h3>  
  27.                         </td>  
  28.                         <tr style="height: 30px; background-color:#d1d6dc ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  29.                             <td align="center">  
  30.                                 <div id="reactContent" style="color:red"></div>  
  31.   
  32.                             </td>  
  33.                         </tr>  
  34.                 </table>  
  35.             </td>  
  36.             </tr>  
  37.     </table>  
  38.   
  39.   
  40.     <br />  
  41.     <script src="http://fb.me/react-0.13.1.js"></script>  
  42.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  43.     <script src="~/Scripts/jquery-1.10.2.js"></script>  
  44.     <script src="~/Scripts/shanuWebAPISample.jsx"></script>  
  45. </body>  
  46.   
  47. </html>  
When we run the program we can see the following output.

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:
  1. USE MASTER  
  2. GO  
  3.   
  4. --1) Check  
  5. for the Database Exists.If the database is exist then drop and create new DB  
  6. IF EXISTS(SELECT[nameFROM sys.databases WHERE[name] = 'ItemDB')  
  7. DROP DATABASE ItemDB  
  8. GO  
  9.   
  10. CREATE DATABASE ItemDB  
  11. GO  
  12.   
  13. USE ItemDB  
  14. GO  
  15.   
  16. --1) //////////// StudentMasters   
  17.   
  18. IF EXISTS(SELECT[nameFROM sys.tables WHERE[name] = 'ItemDetail')  
  19. DROP TABLE ItemDetail  
  20. GO  
  21.   
  22. CREATE TABLE[dbo].[ItemDetail](  
  23.     [ItemID] INT IDENTITY PRIMARY KEY, [ItemName][varchar](100) NOT NULL, [Desc][varchar](100) NOT NULL, [Price][varchar](20) NOT NULL  
  24. )  
  25.   
  26. --insert sample data to itemDetails table  
  27. INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])  
  28. VALUES('NoteBook''HP Notebook 15 Inch''24500')  
  29.   
  30. INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])  
  31. VALUES('MONITOR''SAMSNG''8500')  
  32.   
  33. INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])  
  34. VALUES('MOBILE''SAMSUNG NOTE 5''59500')  
  35.   
  36. INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])  
  37. VALUES('MOUSE''ABKO''780')  
  38.   
  39. INSERT INTO[ItemDetail]([ItemName], [Desc], [Price])  
  40. VALUES('HDD''LG''3780')  
  41.   
  42. 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.

Create WCF REST Service

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.
  1. public interface IService1 {  
  2.   
  3.     [OperationContract]  
  4.     [WebInvoke(Method = "GET",  
  5.         RequestFormat = WebMessageFormat.Json,  
  6.         ResponseFormat = WebMessageFormat.Json,  
  7.         UriTemplate = "/GetItemDetails/")]  
  8.     List < ShanuDataContract.itemDetailsDataContract > GetItemDetails();  
  9.   
  10.     // TODO: Add your service operations here  
  11. }  
  12.   
  13. public class ShanuDataContract {  
  14.     [DataContract]  
  15.     public class itemDetailsDataContract {  
  16.         [DataMember]  
  17.         public string ItemID {  
  18.             get;  
  19.             set;  
  20.         }  
  21.   
  22.         [DataMember]  
  23.         public string ItemName {  
  24.             get;  
  25.             set;  
  26.         }  
  27.   
  28.         [DataMember]  
  29.         public string Desc {  
  30.             get;  
  31.             set;  
  32.         }  
  33.   
  34.         [DataMember]  
  35.         public string Price {  
  36.             get;  
  37.             set;  
  38.         }  
  39.   
  40.   
  41.     }  
  42. }  
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.

Entity Data Model

Select EF Designer from the Database and click "Next".

Next

Click "New Connection".

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.

ItemDB

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.

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.
  1. public class Service1: IService1 {  
  2.     ItemDBEntities OME;  
  3.     public Service1() {  
  4.         OME = new ItemDBEntities();  
  5.     }  
  6.   
  7.     public List < ShanuDataContract.itemDetailsDataContract > GetItemDetails() {  
  8.         var query = (from a in OME.ItemDetails select a).Distinct();  
  9.   
  10.         List < ShanuDataContract.itemDetailsDataContract > ItemDetailsList = new List < ShanuDataContract.itemDetailsDataContract > ();  
  11.   
  12.         query.ToList().ForEach(rec => {  
  13.             ItemDetailsList.Add(new ShanuDataContract.itemDetailsDataContract {  
  14.                 ItemID = Convert.ToString(rec.ItemID),  
  15.                     ItemName = rec.ItemName,  
  16.                     Desc = rec.Desc,  
  17.                     Price = rec.Price  
  18.             });  
  19.         });  
  20.         return ItemDetailsList;  
  21.     }  
  22. }  
Web.Config

In the WCF project's “Web.Config”, make the following changes:
  1. Change <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />.

    2. Replace the </behaviors> to:
    1. <endpointBehaviors>  
    2.     <behavior>  
    3.         <webHttp helpEnabled="True" />  
    4.     </behavior>  
    5. </endpointBehaviors>  
    6. </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.

WCF Rest service

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.

Web Application

Select MVC and in Add folders and core reference for. Select the Web API and click OK.

MVC

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

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.

add JavaScript File

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.

  1. var ItemDetailList = React.createClass({  
  2.     render: function() {  
  3.   
  4.         var itemTable = this.props.data.map(function(itemarray) {  
  5.   
  6.             return (  
  7.   
  8.                 < ItemArray >  
  9.   
  10.                 < table >  
  11.                 < tr >  
  12.                 < td width = "40" > < /td> < td width = "140"  
  13.                 align = "center" > {  
  14.                     itemarray.ItemID  
  15.                 } < /td> < td width = "240"  
  16.                 align = "center" > {  
  17.                     itemarray.ItemName  
  18.                 } < /td> < td width = "120"  
  19.                 align = "right" > {  
  20.                     itemarray.Price  
  21.                 } < /td> < td width = "420"  
  22.                 align = "center" > {  
  23.                     itemarray.Desc  
  24.                 } < /td> < td > < /td> < /tr> < /table>  
  25.   
  26.   
  27.                 < /ItemArray>  
  28.   
  29.             );  
  30.         });  
  31.         return ( < div > {  
  32.             itemTable  
  33.         } < /div>);  
  34.     }  
  35. });  
  36.   
  37. var ItemArray = React.createClass({  
  38.     render: function() {  
  39.         return ( < div > {  
  40.             this.props.children  
  41.         } < /div>);  
  42.     }  
  43. });  
  44.   
  45. var ItemContainer = React.createClass({  
  46.   
  47.     getInitialState: function() {  
  48.         return {  
  49.             data: []  
  50.         };  
  51.     },  
  52.   
  53.     componentWillMount: function() {  
  54.         var xhr = new XMLHttpRequest();  
  55.         xhr.open('get'this.props.url, true);  
  56.         xhr.onload = function() {  
  57.             var itemData = JSON.parse(xhr.responseText);  
  58.   
  59.             this.setState({  
  60.                 data: itemData  
  61.             });  
  62.         }.bind(this);  
  63.         xhr.send();  
  64.     },  
  65.   
  66.     render: function() {  
  67.         return (  
  68.   
  69.             < ItemDetailList data = {  
  70.                 this.state.data  
  71.             }  
  72.             />  
  73.         );  
  74.     }  
  75. });  
  76.   
  77. 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.

run the program

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!

Up Next
    Ebook Download
    View all
    Learn
    View all