SignalR with JavaScript in ASP.NET Core MVC

SignalR with JavaScript in ASP.NET Core MVC

This blog is going to explain what is SignalR and how to implement it in ASP.NET Core. SignalR is a real time application framework for ASP.NET Core. Using SignalR you can provide updated information without refreshing the page, for example poll results, game score, chat etc. Let's see how to achieve it in ASP.NET Core MVC.

Step 1:
First step I added the SignalR client library. To add a SignalR client library, Right click on the project in Solution Explorer and Add -> Client-Side Library. Select the provider as unpkg as shown in the image below. Enter the latest version of SignalR into the library. And selected signalr.js and signalr.min.js files. Finally clicked the install button to install the client library.

SignalR client library

Step 2:
At this step I have created a VoteHub.cs class inside the Hubs folder(create a new folder called Hubs). This class inherits from the Hub class which is a base class of SignalR hub. The SendMessage method will be called by the connected client.

/Hubs/VoteHub.cs
namespace SignalRWebApplication.Hubs
{
    public class VoteHub : Hub
    {
        public async Task SendMessage(int moanaScore, int lionScore, int frozenScore)
        {
            await Clients.All.SendAsync("ReceiveMessage", moanaScore, lionScore, frozenScore);
        }
    }
}

Step 3:
This Step is a Startup class. In the ConfigureServices() method, the services.AddSignalR() is added to add the SignalR service. The Configure() method added endpoints.MapHub<VoteHub>("/VoteHub") to map the incoming request with the specific path.

Startup.cs
using SignalRWebApplication.Hubs;

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        endpoints.MapHub<VoteHub>("/VoteHub");
    });
}

Step 4:
This step is a view. It has three radio buttons to get the user's favorite movie. Also I have included the signalr.js and vote.js files.

/views/Index.cshtml
Choose your favorite movie
<br />
<label><input type="radio" id="moanaRadio" name="movie" /> Moana</label>
<br />
<label><input type="radio" id="lionRadio" name="movie" /> The Lion King</label>
<br />
<label><input type="radio" id="frozenRadio" name="movie" /> Frozen II</label>

<br />
<br />

<div>Moana Sore: <h4 id="moanaScore">0</h4></div>
<div>The Lion King Sore: <h4 id="lionScore">0</h4></div>
<div>Frozen II Sore: <h4 id="frozenScore">0</h4></div>

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

Step 5:
This step is JavaScript. It creates the start connection, Receive the score and send the score each time when the user selects the favorite movie.

/js/vote.js
"use strict";

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

document.getElementById("moanaRadio").disabled = true;
document.getElementById("lionRadio").disabled = true;
document.getElementById("frozenRadio").disabled = true;

connection.on("ReceiveMessage", function (moanaScore, lionScore, frozenScore) {
    document.getElementById("moanaScore").innerText = moanaScore;
    document.getElementById("lionScore").innerText = lionScore;
    document.getElementById("frozenScore").innerText = frozenScore;
});

connection.start().then(function () {
    document.getElementById("moanaRadio").disabled = false;
    document.getElementById("lionRadio").disabled = false;
    document.getElementById("frozenRadio").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

// Moana Radio Button Click 
document.getElementById("moanaRadio").addEventListener("click", function () {

    var moanaScore = parseInt(document.getElementById("moanaScore").innerText) + 1;
    var lionScore = parseInt(document.getElementById("lionScore").innerText);
    var frozenScore = parseInt(document.getElementById("frozenScore").innerText);

    connection.invoke("SendMessage", moanaScore, lionScore, frozenScore).catch(function (err) {
        return console.error(err.toString());
    });
});

// The Lion king Radio Button  Click 
document.getElementById("lionRadio").addEventListener("click", function () {

    var moanaScore = parseInt(document.getElementById("moanaScore").innerText);
    var lionScore = parseInt(document.getElementById("lionScore").innerText)+1;
    var frozenScore = parseInt(document.getElementById("frozenScore").innerText);

    connection.invoke("SendMessage", moanaScore, lionScore, frozenScore).catch(function (err) {
        return console.error(err.toString());
    });
});

// Frozen II Radio Button  Click 
document.getElementById("frozenRadio").addEventListener("click", function () {

    var moanaScore = parseInt(document.getElementById("moanaScore").innerText);
    var lionScore = parseInt(document.getElementById("lionScore").innerText);
    var frozenScore = parseInt(document.getElementById("frozenScore").innerText)+1;

    connection.invoke("SendMessage",moanaScore, lionScore, frozenScore).catch(function (err) {
        return console.error(err.toString());
    });
});

Output
The image below is the output of the code above. You can see the movie score being updated simultaneously in both windows when the user selects a favorite movie.

SignalR with JavaScript in ASP.NET Core MVC

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Role-Based Authorization in ASP.NET Core MVC