How Can I send Clients value in ASP.NET Controller?

  c#, javascript, jquery, signalr

I have written a code in c#, javascript, using client library SignalR to refresh a page in database value change. My code is

<form asp-action="Start" method="post" class="form-stacked">
    <button type="submit" id="startPractice" class="button-primary">Start Practice</button>
</form>

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

My API method is which is called while clicking start practice is

public async Task<IActionResult> Index(long sessionId)
{
     // Database change logic

     SignalRClientHub sr = new SignalRClientHub();
     await sr.SendMessage();

     // Rest of the logic

     return this.View();
}

 public class SignalRClientHub : Hub
    {
        public async Task SendMessage(string user = null, string message = null)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }

code of chat.js

"use strict";

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

connection.on("ReceiveMessage", function (user, message) {
    location.reload();
});

When I click the button start practice it hits SendMessage Method, but I got an error

object reference not set to an instance

because the value of the Client was null. How Can I fix this?

Source: Ask Javascript Questions

LEAVE A COMMENT