Click here to Skip to main content
14,040,625 members
Click here to Skip to main content
Add your own
alternative version

Stats

45.9K views
1.2K downloads
30 bookmarked
Posted 4 Sep 2015
Licenced CPOL

Getting Started with ReactJS Using MVC And WCF REST

, 9 Sep 2015
Rate this:
Please Sign up or sign in to vote.
In this article you will learn about MVC using ReactJS and WCF Rest for Beginners.

Introduction

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.

<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.


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>

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 above reference links. 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 below:

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" }  ];

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 as BooksList.

var BooksContainer = React.createClass({
    render: function() {
        return (
         <div className="commentBox">
            <h1>Book Details</h1>         
            <BooksList data={this.props.data} />         
          </div>
      );   
    }}
  );

Step 3: In BooksList component I display data one by one from the bookArray component.
Save this below code as html and open in browser: “BookDetailsReactJs.html”.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Shanu 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="bookContainer"></div>
    <script type="text/jsx">

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 (
        <bookArray>
            <b>No.  </b> {book.Count} 
            <b> Author : </b> {book.Author} 
            <b> Book Desc :   </b>   {book.Bookdesc}
            <b> Author Name :  </b> {book.NAMES}
           <br />
        </bookArray>
      );
    });
    return (
      <div >
          {bookDetails}
     </div>
    );
  }
});

var bookArray = React.createClass({
    render: function() {
        return (
          <div >          
        {this.props.children}
        </div>
      );
    }
});

var BooksContainer = React.createClass({
    render: function() {
        return (
          <div className="commentBox">
            <h1>Book Details</h1>     
            <BooksList data={this.props.data} />
                </div>
      );
    }
});

React.render(
  <BooksContainer data={data} />,
  document.getElementById('bookContainer')
);

    </script>
  </body>
</html>

Using the code

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.

 

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

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.


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.
 

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.

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
-- --------------------------------------------

After 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.

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.



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



Click "New Connection".



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.



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.
 

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.

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 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

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 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.

 

Points of Interest

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.

History

shanuFirstReactJS.zip - 2015-09-05

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionVery detailed article ! Pin
Peter.Chan21-Oct-16 5:44
memberPeter.Chan21-Oct-16 5:44 
Question[My vote of 2] thought Pin
Simon_Whale13-Oct-15 1:41
professionalSimon_Whale13-Oct-15 1:41 
AnswerRe: [My vote of 2] thought Pin
syed shanu13-Oct-15 2:07
mvasyed shanu13-Oct-15 2:07 
GeneralMy vote of 4 Pin
Abhishek Kumar Goswami10-Sep-15 1:59
professionalAbhishek Kumar Goswami10-Sep-15 1:59 
QuestionReact.js .net Pin
Sacha Barber8-Sep-15 21:08
mvaSacha Barber8-Sep-15 21:08 
AnswerRe: React.js .net Pin
syed shanu8-Sep-15 21:31
mvasyed shanu8-Sep-15 21:31 
GeneralRe: React.js .net Pin
nanonerd19-Sep-15 4:33
membernanonerd19-Sep-15 4:33 
GeneralRe: React.js .net Pin
syed shanu19-Sep-15 13:46
mvasyed shanu19-Sep-15 13:46 
AnswerRe: React.js .net Pin
Dewey10-Sep-15 7:46
memberDewey10-Sep-15 7:46 
GeneralRe: React.js .net Pin
Sacha Barber10-Sep-15 8:59
mvaSacha Barber10-Sep-15 8:59 
GeneralRe: React.js .net Pin
syed shanu10-Sep-15 14:13
mvasyed shanu10-Sep-15 14:13 
GeneralRe: React.js .net Pin
Dewey17-Sep-15 16:35
memberDewey17-Sep-15 16:35 
GeneralRe: React.js .net Pin
syed shanu17-Sep-15 16:56
mvasyed shanu17-Sep-15 16:56 
QuestionGood Article Pin
Santhakumar Munuswamy @ Chennai4-Sep-15 22:14
professionalSanthakumar Munuswamy @ Chennai4-Sep-15 22:14 
AnswerRe: Good Article Pin
syed shanu4-Sep-15 22:21
mvasyed shanu4-Sep-15 22:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190425.1 | Last Updated 10 Sep 2015
Article Copyright 2015 by syed shanu
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid