HI WELCOME TO SIRIS
Showing posts with label react.js. Show all posts
Showing posts with label react.js. Show all posts

"Hello World" example using ReactJS in asp.net mvc

Leave a Comment

Introduction

This is our first post about ReactJS. Here I have explained a little about ReactJS and What we will learn in this series "ReactJS in ASP.NET MVC application" part by part.

This is the first part of this series. In this post, I will show you very simple "Hello World" example  using ReactJS in asp.net mvc application, where we will create a ReactJS components for show some static message  fetching from server side in our web page.

Server rendered pages are not optional in ReactJS and its one another important features. For make our first example simple I did not use this features in this post. But we will see that very soon.

Just follow the following steps in order to implement "Hello World" example using ReactJS in asp.net MVC application.

Here In this article, I have used Visual Studio 2013 

Step-1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-3: Add new action into your controller for getting the view, where we will implement our first ReactJS component. 

Here I have added "Index" Action into "Home" Controller. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-4: Add view for your Action & design for implement ReactJS component.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code 
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Hello World - ReactJS</h2>
  5. @* HTML for show reactjs component *@
  6.  
  7. <div id="helloworldcontainer">
  8.  
  9. </div>
  10. @* ReactJS javascript (JSX) code *@
  11. @* Jquery library *@
  12. <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  13. @* ReactJS library *@
  14. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
  15. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
  16. @* JSX converter (JSX to native javascript) *@
  17. <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
  18.  
  19. @* Here we will create our first ReactJS Component *@
  20.  
  21. <script type="text/babel">
  22. var HelloWorldComponent = React.createClass({
  23. getInitialState : function(){
  24. return {
  25. serverMessage : ''
  26. };
  27. },
  28. componentDidMount : function(){
  29. //Fetch data from server
  30. $.get('/home/getmessage', function(result){
  31. if(this.isMounted){
  32. this.setState({
  33. serverMessage : result
  34. });
  35. }
  36. }.bind(this));
  37. },
  38. render : function(){
  39. return (<h1>{this.state.serverMessage}</h1>);
  40. }
  41. });
  42.  
  43. ReactDOM.render(<HelloWorldComponent/>,document.getElementById("helloworldcontainer"));
  44. </script>

Here you can see, I have included  react.js, react-dom.js and browser.min.js, and then written few line of js code inside a script node with type set to text/babel. If you see carefully, I have written
<h1>{this.state.serverMessage}</h1>(XML syntax) inside render method, which is called JSX. browser.min.js parse JSX to native javascript code.

Here I have created a React component named "HelloWorldComponent", which contain following 3 methods

  1. getInitialState - Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
  2. componentDidMount - It's a reacts Lifecycle Methods. Invoked once on the client, after rendering occurs. setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
  3. render - This method is required. It always returns a single child element or null or false. Here in this example, we returning <h1> HTML tag with server-side message (JSON data from server-side) 

Step-5: Add an another MVC action for return JSON data for showing in ReactJS component. 

  1. public JsonResult getmessage()
  2. {
  3. return new JsonResult { Data = "Hello World. I am from server-side", JsonRequestBehavior = JsonRequestBehavior.AllowGet};
  4. }

Step-6: Run application.

Displaying tabular data from database using React.js

Leave a Comment
In the previous post, I have shown you "Hello World" example using ReactJS in asp.net mvc. Today I am going to show you, how to display tabular data from a database  (list of data) using React.js, ASP.NET MVC and entity framework.

Fetch data from database and display in tabular format is a very common task in web development. Before this article, I have explained how to fetch data from database in angularjs and how to retrieve and display database data using jquery in MVC.

Today we will see, how to display tabular data from database in ReactJS. Here in this article, we have not implemented paging, sorting and filtering for making the application simple and  understandable. In the next part of this series, we will see paging, sorting and filtering using ReactJS, ASP.NET MVC and entity framework.

Here We will fetch a list of employee data (JSON data) from a database via ajax and then we will create a React component for displaying the employee data list in the tabular format.

Just follow the following steps in order to implement "Displaying tabular data from database using React.js".

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for store data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used a table as below


Employee Table 

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-6: Add new action into your controller for getting the view, where we will implement our ReactJS component. 

Here I have added "Index" Action into "Home" Controller. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-7: Add view for your Action and design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code 
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Display tabular data from database using react js</h2>
  5. @* HTML *@
  6. <div id="griddata" class="container">
  7.  
  8. </div>
  9. @* Bootstrap CSS *@
  10. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  11. @* Jquery *@
  12. <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  13. @* React Library *@
  14. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
  15. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
  16. @* JSX parser library *@
  17. <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
  18. @* ReactJS components *@
  19. <script type="text/babel">
  20. @* Here we will create 2 react component 1 for rows and another for table *@
  21. var EmployeeGridRow = React.createClass({
  22. render : function(){
  23. return (
  24. <tr>
  25. <td>{this.props.item.FirstName}</td>
  26. <td>{this.props.item.LastName}</td>
  27. <td>{this.props.item.EmailID}</td>
  28. <td>{this.props.item.City}</td>
  29. <td>{this.props.item.Country}</td>
  30. </tr>
  31. );
  32. }
  33. });
  34.  
  35. var EmployeeGridTable = React.createClass({
  36. getInitialState: function(){
  37. return {
  38. items:[]
  39. }
  40. },
  41. componentDidMount:function(){
  42. @* Fetch data via ajax *@
  43. $.get(this.props.dataUrl, function(data){
  44. if(this.isMounted()){
  45. this.setState({
  46. items: data
  47. });
  48. }
  49. }.bind(this));
  50. },
  51. render : function(){
  52. var rows = [];
  53. this.state.items.forEach(function(item){
  54. rows.push(<EmployeeGridRow key={item.EmployeeID} item={item}/>);
  55. });
  56. return (<table className="table table-bordered table-responsive">
  57. <thead>
  58. <tr>
  59. <th>First Name</th>
  60. <th>Last Name</th>
  61. <th>Email ID</th>
  62. <th>City</th>
  63. <th>Country</th>
  64. </tr>
  65. </thead>
  66. <tbody>
  67. {rows}
  68. </tbody>
  69. </table>);
  70. }
  71. });
  72. ReactDOM.render(
  73. <EmployeeGridTable dataUrl="/home/getEmployeeData"/>,
  74. document.getElementById('griddata')
  75. );
  76. </script>

Here I have created two React components named "EmployeeGridTable" and "EmployeeGridRow".

Step-8: Add another action to your controller for return  data(employee) list as JSON Data

Here I have used "GetEmployeeData" Action for fetch data. Please write this following code
  1. public JsonResult GetEmployeeData()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. var data = dc.Employees.OrderBy(a => a.FirstName).ToList();
  6. return new JsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  7. }
  8. }

Step-9: Run Application.