Neeraj Purohit
Neeraj Purohit

Reputation: 243

SignalR Issue : Cannot connect to Hub class

I am using SignalR in MVC 5 and trying to create the connection with my Hub class (MyHub.cs) through JavaScript but getting below error message :

Uncaught TypeError: Cannot read property 'client' of undefined

Here is my code from which I am trying to create connection to SignalR :

var client= $.connection.myHub;

I have explored lot on google but not getting any relevant solution. Please help me to figure out this problem.

Thanks in advance.

Upvotes: 0

Views: 1831

Answers (2)

Neeraj Purohit
Neeraj Purohit

Reputation: 243

I have found the solution for this, just remove below line from web.config

<add key="owin:AutomaticAppStartup" value="false" />

It worked for me.

Upvotes: 0

Dhaval Patel
Dhaval Patel

Reputation: 7601

You have to refer below menioned code. My View Has below menioned code

<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function ()
{
    var connectionHub = $.connection.commentHub;
    connectionHub.client.addNewComment = function (comment)
    {

        $("#Comment-list").append("<li>" + comment + "</li>");

    };

    $.connection.hub.start().done(function ()
    {
        $('#valueofcomment').keypress(function (event) {
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                var UserName = '@Session["UserName"].ToString()' + '::' + $("#valueofcomment").val();
                connectionHub.server.addComment(UserName);
                $("#valueofcomment").val("");
                return false;
            }
        });

        $("#InserComment").click(function ()
        {

            var UserName = '@Session["UserName"].ToString()' + '::' + $("#valueofcomment").val();
            connectionHub.server.addComment(UserName);
            $("#valueofcomment").val("");
        });
    });
});
</script>

ignore the inner logic it's my requirement. you have to just look into the method which used in it.

My CommentHub class look like

public class CommentHub:Hub
{
    public void AddComment(string Comment)
    {
        var Context = new SignalREntities();
        Comment com = new Comment();
        com.Comment1 = Comment;
        Context.Comments.Add(com);
        Context.SaveChanges();

        Clients.All.AddNewComment(Comment);


    }

}

Upvotes: 1

Related Questions