Rusty
Rusty

Reputation: 1303

SignalR hubclass in classlibrary

I have a signalr hubclass in a classlibrary

and when i use that hubclass in my webapplication referencing that class library with below javascript code, it does not work,

$(function () {

    var chat = $.connection.notificationHub;

    chat.client.newMessage = function (message) {
        alert(message);

        $('#messages').append('<li><strong>' +  message + '</strong>: </li>');
    };
    $.connection.hub.start();
});

Upvotes: 1

Views: 4336

Answers (1)

Lin
Lin

Reputation: 15188

You need an event to trigger your method in Hub class. See below example:

NotificationHub in the class library

public class NotificationHub : Hub
{
    public void Send(string message)
    {
        Clients.All.newMessage(message);
    }
}

Web application

<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<ul id="messages"></ul>

   <script src="~/Scripts/jquery-1.10.2.min.js"></script>
   <script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
   <script src="signalr/hubs"></script>

    <script>
        $(function () {
            var chat = $.connection.notificationHub;
            chat.client.newMessage = function (data) {
                //alert(data);
                $('#messages').append('<li><strong>' + data + '</strong>: </li>');
            };
            $('#message').focus();
            $.connection.hub.start().done(function () {
                console.log("Connected");
                $('#sendmessage').click(function () {
                    chat.server.send($('#message').val());
                    $('#message').val('').focus();
                });
            });
        });
    </script>

Note

Because you the hubclass is in the class library, you need to install Microsoft ASP.NET SignalR package in it. You also need to install it in the webapplication. Then add hubclass reference to webapplication. Add app.MapSignalR() in your Startup class, like below:

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }

Upvotes: 2

Related Questions