Call JS method from C # using SignalR?

I know that there are many examples related to SignalR, but I can’t get it working, I was hoping that one of you could show (in full) how WebPage we can see how this happens again and again) can cause JS method on the page and change the text label or create a popup or just something that we will see that the method is executed?

I will give you my code and maybe you can point out an error, but any basic example of calling Server-> Client without a click that made the request for the first time will be amazing!

Hub:

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

Call Method (Threaded):

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

JS:

 $(function () { // Proxy created on the fly var chat = $.connection.chat; // Declare a function on the chat hub so the server can invoke it chat.addMessage = function (message) { confirm("Are you having fun?"); confirm(message); }; // Start the connection $.connection.hub.start(); }); 
+4
source share
1 answer

The problem I ran into is the closing JS import tag itself, which stopped all the JS on the page running ...

For other users having the same problem, here is my working example on a server that displays data to all clients without any prompts from the client:

JavaScript:

 $(function () { // Proxy created on the fly var chat = $.connection.chat; // Declare a function so the hub can invoke it chat.addMessage = function (message) { document.getElementById('lblQuestion').innerHTML = message; }; // Start 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) { // Call 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 customers:

 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 DoIt () call:

  var thread = new Thread(new ThreadStart(DoIt)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); 
+2
source

Source: https://habr.com/ru/post/1438989/


All Articles