How can you call a JavaScript function from C# using SignalR?

I have been struggling to get SignalR working despite the many examples available. I am hoping that someone can provide a clear demonstration of how a WebPage with a threaded loop can call a JavaScript method on a page to change a text label or create a popup. Essentially, I would like to see the method in action without the need for the client to make an initial request.

Here is my code, and any guidance on where I may be going wrong would be greatly appreciated. But more importantly, a basic example of server-to-client invocation without a prior request from the client would be fantastic!

Hub:

[HubName("chat")]
public class Chat : Hub
{
    public void Send(string message)
    {
        // Call the addMessage method on all clients?
        Clients.addMessage(message);
    }
}

Threaded method being called:

private void DoIt()
{
    int i = 0;
    while (true)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        hubContext.Clients.addMessage("Doing it... " + i);
        i++;
        Thread.Sleep(500);
    }
}

JavaScript code:

$(function () {
    // Proxy created dynamically
    var chat = $.connection.chat;

    // Define a function on the chat hub for server invocation
    chat.addMessage = function (message) {
        confirm("Are you having fun?");
        confirm(message);
    };

    // Start the connection
    $.connection.hub.start();        
});

Answer №1

One issue that I encountered was a self-closing JS import tag that prevented all JS on the page from running...

For those facing a similar problem, here is an example of how to push data from a server to all clients without any client prompting:

Javascript:

$(function () {
    // Creating a proxy on the fly
    var chat = $.connection.chat;

    // Defining a function for the hub to invoke
    chat.addMessage = function (message) {
        document.getElementById('lblQuestion').innerHTML = message;
    };

    // Starting the connection
    $.connection.hub.start();
});

HTML:

<h2 id="lblQuestion" runat="server">Please wait for a question...</h2>

Hub:

[HubName("chat")]
public class Chat : Hub
{
    public void Send(string message)
    {
        // Calling the addMessage method on all clients
        Clients.addMessage(message);
    }

    public void Broadcast(string message)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        context.Clients.addMessage(message);
    }
}

Calling clients:

private void DoIt()
{
    int i = 0;
    while (true)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<Chat>();
        hubContext.Clients.addMessage("Doing it... " + i);
        i++;
        Thread.Sleep(500);
    }
}

Threaded call to DoIt():

    var thread = new Thread(new ThreadStart(DoIt));

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();

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

How to Retrieve Correct JSON Data from Mongoose Query in Node.js

I am currently working on an express application that utilizes mongoDB as the database and handlebars as my server-side templating engine. Unlike many applications, I have chosen not to incorporate AngularJS or Ajax into my project. One of the challenges ...

Launch current screen inside a jquery dialog box

When attempting to open an existing aspx page within a jQuery dialog, I noticed that the CSS of the parent screen is being overridden by the dialog box. Is there a way to prevent this without making changes to the existing screen? If there are any altern ...

The necessary parameters are not provided for [Route: sender] with the [URI: {name}/{code}]. The missing parameters are name and code

I have encountered a problem while using AJAX and I am struggling to find a solution. Routes: web.php Route::get('/{name}/{code}', 'TestController@counter'); Route::post('/{name}/{code}', 'TestController@sender')-&g ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...

Mongoose and ES6 promises are not delivering the expected results

I'm currently working on a piece of code that involves creating an array of promises to save specific numbers. The issue I'm facing is that when the output is printed, it displays the same record 10 times. Below is the code snippet: 'use s ...

Utilizing jQuery Deferred or Promise to synchronize the completion of multiple asynchronous $.post requests

I'm attempting to make three separate jQuery posts, storing their results in variables that are accessible outside of their scope. Once all three posts have returned successfully, I want to execute another function. Currently, I am using nested callba ...

Troubleshooting a dysfunctional anchor tag in an ASP.NET environment

I'm currently facing an issue with anchors in ASP.NET. Despite setting them up in the same way as you would in standard HTML, such as: <a href="#Intro">Introduction</a> and then further down the page, <a name="Intro" ... for some rea ...

What is the best way to create a TypeScript function similar to a 'map' in React?

I recently started learning TS and am having trouble typing this arrow function: const mapLikeGet = (obj, key) => { if (Object.prototype.hasOwnProperty.call(obj, key)) return obj[key] } ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Delete the JSON object stored in local storage and reconstruct the array from scratch

I've encountered an issue with deleting an item from LocalStorage...here's the JSON data stored in LocalStorage. { "1461569942024" : {"t_id":1461569942024,"t_build_val":"PreBuild1","t_project_val":"18"}, "1461570048166" : {"t_id":1461570048166 ...

Using Three.js: Cloning Mesh and Material to Easily Toggle Clone Opacity

By using the command Mesh.clone();, it is possible to duplicate the mesh. Upon further investigation, I discovered that both the geometry and material are preserved in the clone. However, my goal is to independently adjust the opacity of each mesh. This le ...

What are some best practices for preventing unforeseen rendering issues when utilizing React Context?

I am encountering an issue with my functional components under the provider. In the scenario where I increase counter1 in SubApp1, SubApp2 also re-renders unnecessarily. Similarly, when I increase counter2 in SubApp2, SubApp1 also gets rendered even thou ...

How can you stop VueUse useStorage from filling localStorage again after clearing it?

Using Vue 3 in combination with VueUse's useStorage to sync reactive state with localStorage has presented a challenge for me. Whenever I programmatically clear localStorage during user logout processes, it seems to automatically refill with previous ...

There was a TypeError that was not caught in the promise, stating that the function window.showOpenFilePicker is not valid

Encountering TypeError with File System Web API While experimenting with the File System Web API, I keep receiving a TypeError stating Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function. I am unsure of what is causing this issue. ...

Creating a JavaScript/jQuery function for summing input values within an array

I am currently working on developing a function that can add elements from input fields into an array: function addPersonToDatabase(userId){ var name = $('#name').val(); var surname = $('#surname').val(); var age = $(' ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

What is the reason behind JSON.parse returning null when the parameter is null?

When null is passed to JSON.parse, it returns null without any explanation in the documentation. Is there a specific reason for this behavior? Some other things to consider: This might be related to type conversion, as even passing JSON.parse("null") res ...

Tips for adding a dynamic variable into a react JSX map function

I have a component that receives a props with the value of either 'A', 'B', or 'C' based on the selection made in the parent element. The challenge is to use this props to dynamically select an option list locally, instead of ...

Utilize AngularJS to Access Global JavaScript Variables

I recently encountered a situation where I needed to incorporate some dynamic functionality into a website I was building. This led me to AngularJS, which I decided to integrate into certain parts of the site rather than the entire thing. Within my JavaSc ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...