In this article, you will learn about MVC using ReactJS and WCF Rest for beginners.
Introduction
The main aim of writing this article is that there are lot of articles and samples related to MVC and AngularJS but there are not many articles and examples related to ReactJS and MVC and also there is no proper article that has samples which explain how to display data from SQL Server database 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 the following in detail:
- 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
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 results 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 the 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 you now 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
Similar to the 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 far, we have seen a sample program using HTML and ReactJS. Now we see how to use ReactJS in MVC.
Prerequisites
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 has been created, the 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 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 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
USE MASTER
GO
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, now first, let’s create 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
methods 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 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 that 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" />
- 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 has been 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
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 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 four 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 for reading.
History
- 5th September, 2015: Initial version