Integration with C# and ReactJS

The goal for this project is to show a list of books with ReactJS from a WebAPI written in C#. You can download this project from Github.

New project

Start by creating a new ASP.NET MVC 4 project: 1. File → New → Project 2. Select ".NET Framework 4" and Templates → Visual C# → Web → ASP.NET MVC 4 Web Application. Call it "CSReact" 3. In the "New ASP.NET MVC 5 (or 4) Project" dialog, select the MVC (or empty) template.

Install ReactJS.NET

We need to install ReactJS.NET to the newly-created project. This is accomplished using NuGet, a package manager for .NET. Right-click on the "ReactDemo" project in the Solution Explorer and select "Manage NuGet Packages". Search for "ReactJS.NET" and install the ReactJS.NET (MVC 4 and 5) package.

Create basic controller and view

Right-click on the Controllers folder and click Add → Controller. Name the controller "HomeController" and select "Empty MVC Controller" as the template. Once the controller has been created, right-click on return View() and click "Add View". Enter the following details:

  • View name: Index
  • View Engine: Razor (CSHTML)
  • Create a strongly-typed view: Unticked
  • Create as a partial view: Unticked
  • Use a layout or master page: Unticked

Replace the contents of the new view file with the following:

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>
            <p>
            </p>
        </div>
    </section>
}
<h3>React here:</h3>
<div id="content"></div>

@section scripts {
    <script src="https://fb.me/react-0.14.0.min.js"></script>
    <script src="https://fb.me/react-dom-0.14.0.min.js"></script>
    <script src="@Url.Content("~/Scripts/pages/books.jsx")"></script>
}

We also need to create the referenced JavaScript file books.jsx. Right-click on Scripts folder, select Add > New Folder, and enter "pages" as the folder name. Once created, right-click on the folder and select Add > New Item. Select Web > JavaScript File, enter "books.jsx" as the file name, and click "Add".

Create a model

Under Models folder add a new class called BookModels with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CSReact.Models {
   /// <summary>
   /// Book models
   /// </summary>
   public class BookModels {
      /// <summary>
      /// Title of the book
      /// </summary>
      public string Title { get; set; }

      /// <summary>
      /// Author of the book
      /// </summary>
      public string Author { get; set; }
   }
}

Generate WebAPI for Books

To generate a WebAPI right-click on Controllers folder and then you select Add → Controller. Choose now WebAPI 2 Controller - Empty and type Books. The API name will be BooksController.

Fill in the controller the following code:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Script.Serialization;
using CSReact.Models;
using Newtonsoft.Json.Serialization;

namespace CSReact.Controllers
{
    public class BooksController : ApiController
    {
       public HttpResponseMessage Get() {
          IList<BookModels> result = new List<BookModels>();
          result.Add(new BookModels() { Author = "Michael Crichton", 
                                        Title = "Jurassic Park" });
          result.Add(new BookModels() { Author = "Agatha Christie", 
                                        Title = "And Then There Were None" });

          var formatter = new JsonMediaTypeFormatter();
          var json = formatter.SerializerSettings;

          json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
          json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
          json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
          json.Formatting = Newtonsoft.Json.Formatting.Indented;
          json.ContractResolver = new CamelCasePropertyNamesContractResolver();
          json.Culture = new CultureInfo("en-GB");

          return Request.CreateResponse(HttpStatusCode.OK, result, formatter);
       }
    }
}

This API reply on your local server. You can call your API with an URL similar to

http://localhost:60273/api/books

and the result in the browser is a json result

[
  {
    "title": "Jurassic Park",
    "author": "Michael Crichton"
  },
  {
    "title": "And Then There Were None",
    "author": "Agatha Christie"
  }
]

Generate a book list

In the books.jsx file write the following code:

var BookList = React.createClass({
    render: function() {
        var bookNodes = this.props.data.map(function (book) {
            return (
                <div>
                    {book.title} ({book.author})
                </div>
            );
        });

        return (
            <div className="bookList">
                {bookNodes}
            </div>
        );
    }
});

This function will receive as a property data. data will contain the list of books that it has read from our WebAPI. For each row in data (you can read for each book in data), it creates a new div with title and author from book. The function returns a new div within the list of book.

Then we can write the other part of the books.jsx where you read the data from the WebAPI and display it calling BookList function. The complete code of books.jsx is

var BookList = React.createClass({
    render: function() {
        var bookNodes = this.props.data.map(function (book) {
            return (
                <div>
                    {book.title} ({book.author})
                </div>
            );
        });

        return (
            <div className="bookList">
                {bookNodes}
            </div>
        );
    }
});

var App = React.createClass({
    getInitialState: function() {
        return {data: []};
    },

    componentDidMount: function() {
        $.get(this.props.url, function(result) {
            var book = result[0];
            if (this.isMounted()) {
            }
        }.bind(this));
    },

    componentWillMount: function() {
        var xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = function() {
            var jdata = JSON.parse(xhr.responseText);
            this.setState({ data: jdata });
        }.bind(this);
        xhr.send();
    },

    render: function() {
        return (
          <div className="commentBox">
            <BookList data={this.state.data} />
          </div>
      )
    }
});

ReactDOM.render(
  <App url="/api/books/Get" />,
  document.getElementById('content')
);

If you're lucky and try to start your app, you can see the list of books in your index page.

Add comment

Advertsing

125X125_06

CommentList

  • None