SignalR- Jquery : $.connection.chathub returns undefined

此生再无相见时 提交于 2019-12-25 08:48:21

问题


I'm creating a chat application using Asp.net MVC, AngularJs, SignalR and Jquery. In the Chat View when I'm trying set the value for chat object it passes null value the code reference is inside the brackets ( var chat=$.connection.chathub;). No other function works because of this. I'm using "Microsoft.AspNet.SignalR.2.2.2" in this project. And jquery and signalr related scripts such as 'jquery.signalR-2.2.2.js ,jquery-ui-1.12.1.js' and few other jquery libraries as well.

Can anyone help me out? I have attached the code for your reference.

@section scripts{
    @*@Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")
        @Scripts.Render("~/Scripts/jquery.signalR-2.2.2.min.js")*@

    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

    <script type="text/javascript">


        $(function () {
            StartChat();
        });



        function StartChat() {
            alert('StartChat');
            var chat = $.connection.chathub;
            alert('chat : ' + $.connection.chathub);
            // Get logged in user
            $('#UserIn').val($('#LoggedInUser').val());
            chat.client.differentName = function (name) {
                return false;
                // Prompts for different user name
                $('#UserIn').val($('#LoggedInUser').val());
                chat.server.notify($('#UserIn').val(), $.connection.hub.id);
            };

            chat.client.online = function (name) {
                // Update list of users
                if (name == $('#UserIn').val())
                    $('#onlineusers').append('<div class="border" style="color:green">You: ' + name + '</div>');
                else {
                    $('#onlineusers').append('<div class="border">' + name + '</div>');
                    $("#users").append('<option value="' + name + '">' + name + '</option>');
                }
            };

            //
            chat.client.enters = function (name) {
                $('#chatlog').append('<div ><i>' + name + ' joins the conversation</i></div>');
                $("#users").append('<option value="' + name + '">' + name + '</option>');
                $('#onlineusers').append('<div class="border">' + name + '</div>');
            };

            // Create a function that the hub can call to broadcast chat messages.
            chat.client.broadcastMessage = function (name, message) {

                //display the message
                $('#chatlog').append('<div class="border"><span style="color:orange">' + name + '</span>: ' + message + '</div>');
            };

            chat.client.disconnected = function (name) {
                //Calls when someone leaves the page
                $('#chatlog').append('<div ><i>' + name + ' leaves the conversation</i></div>');
                $('#onlineusers div').remove(":contains('" + name + "')");
                $("#users option").remove(":contains('" + name + "')");
            };

            // start the connection
            $.connection.hub.start().done(function () {
                alert('Send button clicked : ' + $('#message').val());
                //Calls the notify method of the server
                chat.server.notify($('#UserIn').val(), $.connection.hub.id);

                $('#btnsend').click(function () {
                    alert('Send button clicked : ' + $('#message').val());
                    // Call the Send method on the hub.
                    chat.server.send($('#UserIn').val(), $('#message').val());


                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            })
        }
    </script>
}
@model ZupChatApp.Models.User
@{
    ViewBag.Title = "ChatRoomView";
}





@Html.Label("LoggedInUser", Model.FirstName, new { id = "" })
<h2>Zup Chat Room View</h2>
<div class="LeftContent">

    abcccc
</div>
<div class="CenterContent">
    <div id="container">
        <input type="hidden" id="nickname" />
        <div id="chatlog"></div>
        @*<div id="onlineusers">
                <b>Online Users</b>
            </div>*@
        <div id="chatarea">
            <div class="messagelog">
                <textarea spellcheck="true" id="message" class="messagebox"></textarea>
            </div>
            <div class="actionpane">
                <input type="button" id="btnsend" value="Send" class="btn btn-success col-md-offset-2 glyphicon-font" />
            </div>

        </div>
    </div>
</div>
<div></div>

回答1:


You should always start with an exact copy of the sample from Microsoft. Not just for the page but the whole solution. Get the sample solution working.

This is true for any technology with which you are unfamiliar. Then start modifying things one thing at a time to arrive at your arrangement.

And, this is my page that worked (from a while ago). Compare and see what is different:

@section scripts {
  <!--Reference the SignalR library. -->
  <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
  <!--Reference the autogenerated SignalR hub script. -->
  <script src="~/signalr/hubs"></script>

  <!--Add script to update the page and send messages.-->
  <script type="text/javascript">
    $(function () {
      // Declare a proxy to reference the hub.
      var chat = $.connection.chatHub;
      // Create a function that the hub can call to broadcast messages.
      chat.client.broadcastMessage = function (customMessage) {
        // Html encode display name and message.
        var encodedName = $('<div />').text(customMessage.UserName).html();
        var encodedMsg = $('<div />').text(customMessage.Message).html();
        // Add the message to the page.
        $('#discussion').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
      };
      // Get the user name and store it to prepend to messages.
      $('#displayname').val(prompt('Enter your name:', ''));
      // Set initial focus to message input box.
      $('#message').focus();
      // Start the connection.
      $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
          // Call the Send method on the hub.
          chat.server.sendCustomMessage({ "UserName": $('#displayname').val(), "Message": $('#message').val() });
          // Clear text box and reset focus for next comment.
          $('#message').val('').focus();
        });
      });
    });
  </script>

}

<div class="container">
  <input type="text" id="message" />
  <input type="button" id="sendmessage" value="Send" />
  <input type="hidden" id="displayname" />
  <ul id="discussion"></ul>
</div>



回答2:


This is probably an issue with the casing of chathub. From the "Getting Started with SignalR 2" documentation:

In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub.

So, change it to

var chat = $.connection.chatHub;

Also, <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script> reference should be added before <script src="~/signalr/hubs"></script>



来源:https://stackoverflow.com/questions/46499218/signalr-jquery-connection-chathub-returns-undefined

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