Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple example of signalR not working

Tags:

signalr

Not able to get SignalR working in my machine (with IE9). On entering some text and clicking submit, the text is not getting listed as intended. Also, I would expect the list getting updated from multiple instances of browser and It does not happen. There is no error. Could anybody help here?

C#

namespace TestSignalR.Hubs
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    /// <summary>
    /// Summary description for ChatHub.
    /// </summary>
    public class ChatHub : SignalR.Hubs.Hub
    {
        public void TestMessage(string message)
        {
            Clients.writeMessage(message);
        }
    }
}

ASPX

<input type="text" name="txtInput" id="txtInput" />
<button id="btnSubmit">Submit</button>

<ul id="messages">
</ul>
<script type="text/javascript" src="SignalR/Hubs"></script>
<script type="text/javascript">
    $(document).ready(function (message) {
        var chat = $.connection.chatHub;

        chat.writeMessage = function (message) {
            $("#messages").append("<li>" + message + "</li>");
        };

        $("#btnSubmit").click(function () {
            var text = $("#txtInput").val();
            chat.testMessage(text);
        });

        $.connection.hub.start();
    });

</script>

Master page has the references for the JQuery and SignalR files:-

<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
like image 267
user1422578 Avatar asked Oct 23 '22 16:10

user1422578


1 Answers

Today I was working with the same issue.

First you need to add an atribute to your Hub with the name, as following:

[HubName("chathub")]
public class ChatHub : SignalR.Hubs.Hub

The next to do is to change the order of your calls in the javascript. You need to do the connection next to instantiate the hub. So, the code will be as following:

$(document).ready(function (message) {
   var chat = $.connection.chatHub;

   $.connection.hub.start();

   chat.writeMessage = function (message) {
      $("#messages").append("<li>" + message + "</li>");
   };

    $("#btnSubmit").click(function () {
        var text = $("#txtInput").val();
        chat.testMessage(text);
    });        
 });

I hope it works for you.

like image 179
Ignacio Berra Avatar answered Jan 02 '23 19:01

Ignacio Berra