Share via


Getting Started with ReactJS Using MVC And WCF REST

Note: You can download the Source Code  from the link ** Source Code Download Link
**

Introduction

https://code.msdn.microsoft.com/site/view/file/142250/1/1.jpg

 

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.

Building the Sample

1. ReactJS and our first Program

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

<script src="https://fb.me/react-0.13.3.js"></script> 
 <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>

**Step 2: **In your html body tag declare div tag and give the proper id (name) for the div tag.From ReactJS we display all the result to this div tag.

<div id="myName"></div>

Step 3: Create our first ReactJS script. Here we add the type as ="text/jsx".

<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 below sample we can see we bind the NameDisplay component to DOM.

React.render( 
  <NameDisplay  />, 
  document.getElementById('myName') 
);

Step 5: **createClass- **We can create our own custom component by using React.createClass. We can see the below example here I have create a custom component as 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.

var NameDisplay = React.createClass({ 
  render: function() { 
    return ( 
      <div > 
        my Name is Shanu,Welcome to ReactJS. 
      </div>

Here is Complete HTML Source Code when we run this below code in browser we see the output like below.

https://code.msdn.microsoft.com/site/view/file/142252/1/2.jpg

Save this below code as html and open in browser: “shanuFirstReactJS.html”. 

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8" /> 
    <title>Welcome to ReactJs</title> 
    <script src="https://fb.me/react-0.13.3.js"></script> 
    <script src="https://fb.me/JSXTransformer-0.13.3.js"></script> 
  </head> 
  <body> 
    <div id="myName"></div> 
   <script type="text/jsx"> 
var NameDisplay = React.createClass({ 
  render: function() { 
    return ( 
      <div > 
        my Name is Shanu,Welcome to ReactJS. 
      </div> 
    ); 
  } 
}); 
  
React.render( 
  <NameDisplay  />, 
  document.getElementById('myName') 
); 
    </script> 
  </body> 
</html>

Description

So for we have seen a sample program using html and ReactJS .Now we 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 our Visual Studio 2015, click Start -> Programs then select Visual Studio 2015 then click Visual Studio 2015.

Click New -> Project then select Web -> ASP.NET Web Application. Select your project location and enter your web application name.

https://code.msdn.microsoft.com/site/view/file/142254/1/4.jpg

Select MVC and in Add Folders and Core reference for. Select the Web API and click OK.

https://code.msdn.microsoft.com/site/view/file/142255/1/5.jpg

Once our MVC application created next step is to add ReactJS to our application.

Home Controller
In your home controller add the below 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 - > Select ReactJS tools for ASP.NET MVC 4 and 5 and click Install.

 

https://code.msdn.microsoft.com/site/view/file/142256/1/6.jpg

Creating our JSX file

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.
  

https://code.msdn.microsoft.com/site/view/file/142257/1/7.jpg

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/GetMessage" />, document.getElementById('reactContent'));

Code part Explanation:

React.render(<App url="/Home/GetMessage" />, 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 renderd(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 add 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> 
  
    <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 output like below.

https://code.msdn.microsoft.com/site/view/file/142258/1/8.jpg

4.Create ReactJS using MVC and WCF Rest Service to display the data from Database.

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 the result from database to MVC page using ReactJS and WCF REST.

Create Database and Table

-- =============================================                                  
-- Author      : Shanu                                   
-- Create date : 2015-07-13                                     
-- Description : To Create Database,Table and Sample Insert Query                               
-- Latest                                  
-- Modifier    : Shanu                                   
-- Modify date : 2015-07-13                               
-- =============================================   
--Script to create DB,Table and sample Insert data   
  
USE MASTER   
GO   
  
-- 1) Check 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     
  
-- 1) //////////// StudentMasters   
    
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 sample data to itemDetails table   
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 
-- --------------------------------------------

fter creating our Database and table now let’s create first our WCF Rest Application

Create WCF REST Service

Create our MVC web application in Visual Studio 2015. After installing our Visual Studio 2015, click Start -> Programs then select Visual Studio 2015 then click Visual Studio 2015.

Open Visual Studio 2015 then select "File" -> "New" -> "Project..." then select WCF Service Application then select your project path and name your WCF service and click OK.

https://code.msdn.microsoft.com/site/view/file/142259/1/9.jpg

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(); 
              // TODO: Add your service operations here 
       } 
        
       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 tehn select ADO.NET Entity Data Model and click Add.

https://code.msdn.microsoft.com/site/view/file/142263/1/10.jpg

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

https://code.msdn.microsoft.com/site/view/file/142260/1/11.jpg

Click "New Connection".

https://code.msdn.microsoft.com/site/view/file/142261/1/12.jpg

Here we can select our Database Server Name and enter your DB server SQL Server Authentication User ID and Password. We have already created our database as “ItemDB” so we can select the database and click OK.

https://code.msdn.microsoft.com/site/view/file/142262/1/13.jpg

Click Next and select tables that need to be used. In our example we need to use “ItemDB " and “ItemDetail”. Select both tables and click "Finish".

Here we can see that now we have created our ItemDataModel.

https://code.msdn.microsoft.com/site/view/file/142264/1/14.jpg

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:

  1. Change <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />
  2. Replace the </behaviors> to:
<endpointBehaviors>   
       <behavior>  
             <webHttp helpEnabled="True"/>   
        </behavior>   
 </endpointBehaviors>

Run WCF Service

Now we have created our WCF Rest service, let's run and test our service.Here we can see the result.

https://code.msdn.microsoft.com/site/view/file/142265/1/15.jpg

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.

https://code.msdn.microsoft.com/site/view/file/142254/1/4.jpg

Select MVC and in Add Folders and Core reference for. Select the Web API and click OK.

 

https://code.msdn.microsoft.com/site/view/file/142255/1/5.jpg

Once our MVC application created 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. 

https://code.msdn.microsoft.com/site/view/file/142256/1/6.jpg

Creating our JSX file

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.
  

https://code.msdn.microsoft.com/site/view/file/142257/1/7.jpg

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 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 here I have passed the URL as my WCF URL as “http://localhost:39290/Service1.svc/getItemDetails/” .Here I get the result and display the data as tabular form inside div tag

When we run the program we can see the output like below.

https://code.msdn.microsoft.com/site/view/file/142250/1/1.jpg

More Information

Note: In my attached Zip file you can find all 4 Source Sample 2 for HTML sample and one for MVC and Web ApI and one for MVC and WCF Rest using ReactJS. Hope you like this article Thank You.

Note: You can download the Source Code  from the link ** Source Code Download Link**