Simple example of signalR not working

五迷三道 提交于 2019-12-06 02:48:56

问题


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>

回答1:


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.




回答2:


Please install the 1.0 version of SignalR from Nuget as well. From your script references it looks like you are using 0.5.2 and the latest supported version at the time of writing this post is 1.0. Please download Microsoft.AspNet.SignalR from Nuget



来源:https://stackoverflow.com/questions/11425356/simple-example-of-signalr-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!