left-icon

Real-Time ASP.NET Core 3 Apps with SignalR Succinctly®
by Dirk Strauss

Previous
Chapter

of
A
A
A

CHAPTER 11

Creating the Chart Client Application

Creating the Chart Client Application


In the realtimechart project, expand the Pages folder and edit the Index.cshtml file.

Index Page for Realtime Chart

Figure 35: Index Page for Realtime Chart

You will see the following default HTML code, as shown in Code Listing 25.

Code Listing 25

@page

@model IndexModel

@{

    ViewData["Title"] = "Home page";

}

<div class="text-center">

    <h1 class="display-4">Welcome</h1>

    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

</div>

Replace the code in the Index.cshtml file with the code in Code Listing 26.

Code Listing 26

@page

<form>   

    <div class="form-group">

        <label for="messageInput">Value</label>

        <input class="form-control" placeholder="Enter a value" type="text" id="valueInput" />

    </div>

    <div class="form-group">

        <input class="btn btn-primary" type="button" id="sendButton" value="Enter Value" />

    </div>

</form>

<div class="row">

    <div class="col-12">

        <hr />

    </div>

</div>

<div id="chartArea">

</div>

@section Scripts

{

    <script src="~/js/signalr/dist/browser/signalr.js"></script>

    <script src="~/js/charting.js"></script>

}

The code in Code Listing 26 simply adds a text box and a Submit button to your page. There is also a div called chartArea that will display all the chart values received from the SignalR hub and plot them on the chart.

At the bottom of the code, you will see script references to signalr.js and charting.js. I have added these to a Scripts section. We have not added the charting.js file to our project yet. We will do this in a minute. First, I want to add the required references to Chartist to generate the line chart on our page.

 Note: You can read more about Chartist here.

Expand the Pages folder in your solution, and then expand the Shared folder.

Edit the _Layout Page

Figure 36: Edit the _Layout Page

Inside the Shared folder, you will see the _Layout.cshtml page.

Tip: For all the ASP.NET Web Pages devs out there, think of this as a Master Page.

In the <head> section of the _Layout.cshtml page, add a reference to the chartist.min.css file served from the CDNJS (content delivery network – JavaScript) on GitHub, as seen in Code Listing 27.

Code Listing 27

<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">

At the bottom of the _Layout.cshtml page, add a reference to the chartist.min.js file served from the CDNJS in GitHub, as seen in Code Listing 28.

Code Listing 28

<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>

You can find the js and css files here. The complete _Layout.cshtml page will look like Code Listing 29.

Code Listing 29

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>@ViewData["Title"] - realtimechart</title>

    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />

    <link rel="stylesheet" href="~/css/site.css" />       

    <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">

</head>

<body>

    <header>

        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">

            <div class="container">

                <a class="navbar-brand" asp-area="" asp-page="/Index">realtimechart</a>

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"

                        aria-expanded="false" aria-label="Toggle navigation">

                    <span class="navbar-toggler-icon"></span>

                </button>

                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">

                    <ul class="navbar-nav flex-grow-1">

                        <li class="nav-item">

                            <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>

                        </li>

                        <li class="nav-item">

                            <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>

                        </li>

                    </ul>

                </div>

            </div>

        </nav>

    </header>

    <div class="container">

        <main role="main" class="pb-3">

            @RenderBody()

        </main>

    </div>

    <footer class="border-top footer text-muted">

        <div class="container">

            &copy; 2020 - realtimechart - <a asp-area="" asp-page="/Privacy">Privacy</a>

        </div>

    </footer>

    <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>

    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

    <script src="~/js/site.js" asp-append-version="true"></script>   

    @RenderSection("Scripts", required: false)

</body>

</html>

You will notice the @RenderSection("Scripts", required: false) at the bottom of this page. It is from here that the Scripts section mentioned in Code Listing 26 is called.

We are now ready to add our charting.js file to the project. To do this, right-click your js folder (located in wwwroot) and add a new JavaScript file, as illustrated in Figure 37.

Adding a New .js File

Figure 37:Adding a New .js File

Call the file charting.js and click Add. Your solution should now look as illustrated in Figure 38.

Added charting.js File to Project

Figure 38: Added charting.js File to Project

After adding your charting.js file, you should see the blank code editor. Add the following JavaScript code to your charting.js file.

Code Listing 30

"use strict";

var lineChart = new Chartist.Line('#chartArea', {

    labels: [],

    series: [[]]

},

    {

        low: 0,

        showArea: true

    });

var connection = new signalR.HubConnectionBuilder().withUrl("/chartHub").build();

//Disable send button until connection is established.

document.getElementById("sendButton").disabled = true;

connection.on("ValueReceiver", function (chartValue) {

    if (chartValue && !isNaN(chartValue)) {

        lineChart.data.series[0].push(chartValue);

        lineChart.update();

        document.getElementById("valueInput").value = "";

        document.getElementById("valueInput").focus();

    }   

});

connection.start().then(function () {

    document.getElementById("sendButton").disabled = false;

}).catch(function (err) {

    return console.error(err.toString());

});

document.getElementById("sendButton").addEventListener("click", function (event) {

    var strValue = document.getElementById("valueInput").value;

    var chartValue = parseFloat(strValue);

    connection.invoke("ValueSender", chartValue).catch(function (err) {

        return console.error(err.toString());

    });

    event.preventDefault();

});

$('#valueInput').keypress(function (e) {

    var key = e.which;

    if (key === 13)  // the enter key code.

    {

        $('#sendButton').click();

        return false;

    }

});

You will notice that I have not added any validation of inputs in this JavaScript code. If you want to validate the user input, I suggest doing it in the charting.js file.

Let’s have a look at some of the portions of this JavaScript code next.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.