Notifying the view with a SignalR message from the controller upon event trigger

Just starting out with SignalR and attempting to set up a notification for a specific event triggered by an API.

What I've attempted:

Hub:

public class NotificationHub : Hub
{        
    private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

    public static void Send(string content)
    {
        hubContext.Clients.All.addMessage(content);
    }
}

Controller:

//static event from external API
public static void onTick(Tick TickData)
{
    if(TickData.InstrumentToken == buy.InstrumentToken)
    {                   
        NotificationHub.Send(TickData.Bid);   
    } 
}

How can I display the message triggered by this condition in the View?

Attempted View:

$(document).ready(function () {
    var conn = $.connection.NotificationHub;
    conn.client.addMessage = function (message) {
        alert(message);
    };

});

Is there anything else I need to do to make this work?

Edit:

Ashley's response brought me closer, however, a couple of things were missing such as:

  • `connection.NotificationHub` should be `connection.notificationHub`

  • The order of the JavaScript files references should be:

1. jquery-1.10.2.min.js
2. jquery.signalR-2.1.0.min.js
3. signalr/hubs

But now when executing it, it enters the `.fail(function()` and the console shows an error: . Failed to load resource: net::ERR_CONNECTION_REFUSE

Please provide guidance. Thank you in advance.

Answer №1

Ensure that you have the SignalR hubs source code included:

<script type="text/javascript" src="~/signalr/hubs"></script>

To establish a connection for SignalR, make sure to add this snippet of code:

$.connection.hub.start().done(function() {
    //Connection established successfully
}).fail(function() {
    //Failed to start the connection
});

If we use your example, it will look like this:

$(document).ready(function () {
    var conn = $.connection.NotificationHub;
    conn.client.addMessage = function (message) {
        alert(message);
    };

    $.connection.hub.start().done(function() {
        //Connection established successfully
        alert("connected");
    }).fail(function() {
        //Failed to start the connection
        alert("failed");
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...

What steps can be taken to resolve the issue of "Access Denied: Invalid token, incorrect code"?

Assigned to me recently for a school project is a coding challenge that consists of various parts. The final task involves uploading to a private GitHub repository and submitting a completion request through a POST request under specific conditions. I hav ...

Displaying information on an Angular user interface grid

I am facing an issue with displaying data in a UI grid table. I have set up an API through which I can access the data in my browser, but I am encountering difficulties when it comes to rendering the data. Below is my Angular controller where I have defin ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

Issue with rendering partials in ExpressHandlebars in NodeJS

I am currently facing an issue while working with express-handlebars. I am attempting to use partials, but I keep encountering the following error message: The partial header could not be found. In my app.js file, the code appears as follows: var expr ...

Choosing the fourth cell in every row of a table and converting the information

Currently, I am working on a function that is supposed to take the fourth column in each row of a specific table, manipulate the data using a function, and return different data for the cell. This function takes an integer representing total minutes as i ...

Challenge involving CSS and Javascript for solving puzzles

In my attempt to create a puzzle with 2 rows and 3 columns using CSS and JavaScript, I envision the pieces of the puzzle being black and cut into various shapes. The objective is for users to drag these pieces onto the board in order to complete it. I have ...

Even with e.preventDefault, the anchor link still opens in a new tab on the browser

I am dealing with an ajax call that triggers a REST API to return a list of all names, as well as another REST API that matches those names. For instance: /list returns: list1, list2, list3 and /api/list1.json returns: JSON data for list1.. Currently, ...

Implementing an onclick function to initiate a MySQL update query

<?php include_once("db.php"); $result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'"); while($row=mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['ptype'] . "</td>"; echo "<td>" . $row[&apo ...

Using Vue.js - Incorporate filtering functionality within the v-for loop

I've successfully implemented a Vue filter that restricts the length of an array to n elements. It functions perfectly when used like this: {{ array | limitArray(2) }} Now, I'm attempting to utilize it within a v-for loop as follows: <li v- ...

Modifying the height of the bar in Google Charts Timeline using react-google-charts

I am currently working on a Google Chart timeline using react-google-charts. <Chart chartType="Timeline" data={data} width="100%" options={{ allowHtml: true bar: { groupWidth: 10 }, }} ...

encountering a glitch while using console.log(util.format

Let me start by saying that I am fairly new to working with node.js. A friend of mine assisted me in writing the code snippet below. I have successfully installed the necessary packages search-google-geocode, csv-parser, fs, util, and async using npm. H ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

The animation function occasionally halts unexpectedly at a varying position

I am facing an issue with an animation function that I have created to animate a list of images. The function takes in parameters such as frames per second, the stopping point, and the list element containing all the images. However, the animation stops un ...

Configuring git npm dependencies to aid in debugging purposes

This is my first time trying to debug a library in my application and I'm not entirely sure how to go about it. I initially installed the library with npm install @react-pdf/renderer, but debugging was proving difficult. Then, I found a useful answer ...

Error: Property 'html' is undefined - AJAX response must be displayed only in a specific div

I encountered an issue: Uncaught TypeError: Cannot read property 'html' of undefined I am working on implementing a voting system for each video on my webpage from a database. I have successfully integrated it using AJAX, but the problem is ...

Using ASP.NET MVC to efficiently save nested collection data

Just dipping my toes into ASP.Net MVC, so please be patient with me. :) I've got a view with nested collections that can be updated by the user. Successfully retrieving updated model data from an AJAX call to the controller. Now I have a model with ...

Steps for sending a POST request to an API with an extensive amount of fields (50 or more)

Struggling with a complex API call that involves submitting all the form data. Finding it difficult to determine the most effective method for sending the serialized data to the API endpoint. One option is to gather all field values into a JavaScript ob ...