【问题标题】:SignalR- Jquery : $.connection.chathub returns undefinedSignalR- Jquery:$.connection.chathub 返回未定义
【发布时间】:2018-03-11 23:20:20
【问题描述】:

我正在使用 Asp.net MVC、AngularJs、SignalR 和 Jquery 创建一个聊天应用程序。 在聊天视图中,当我尝试设置聊天对象的值时,它传递空值,代码引用位于括号内(var chat=$.connection.chathub;)。因此,没有其他功能起作用。 我在这个项目中使用“Microsoft.AspNet.SignalR.2.2.2”。还有 jquery 和 signalr 相关的脚本,例如 'jquery.signalR-2.2.2.js ,jquery-ui-1.12.1.js' 和其他一些 jquery 库。

谁能帮帮我?我已附上代码供您参考。

@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>

【问题讨论】:

  • 我同意阿迪加。如果答案正确,别忘了标记答案:)
  • @toddmo,我也认为是这样,但事实并非如此。知道我在哪里弄错了吗?

标签: jquery asp.net-mvc asp.net-mvc-5 signalr-hub signalr-2


【解决方案1】:

您应该始终从sample from Microsoft 的精确副本开始。不仅针对页面,还针对整个解决方案。让示例解决方案发挥作用。

这适用于您不熟悉的任何技术。然后开始一次修改一件事以达成您的安排。

而且,这是我的页面(从不久前开始)。比较看看有什么不同:

@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>

【讨论】:

  • 感谢您的建议。我会尝试一个新项目。
  • @t4thilina,我知道这似乎让人头疼,但通过这种方式找到错误并构建无错误系统通常不会那么令人沮丧。
【解决方案2】:

这可能是chathub 的大小写问题。来自“SignalR 2 入门”documentation

在 JavaScript 中,对服务器类及其成员的引用采用驼峰式。代码示例将 JavaScript 中的 C# ChatHub 类引用为 chatHub

所以,改成

var chat = $.connection.chatHub;

另外,&lt;script src="~/Scripts/jquery.signalR-2.2.2.min.js"&gt;&lt;/script&gt; 引用应该在&lt;script src="~/signalr/hubs"&gt;&lt;/script&gt; 之前添加

【讨论】:

  • 在我的情况下没有成功。我试着改变它。还有什么问题?
  • @t4thilina 您在~/Scripts/jquery.signalR.js 之前添加了~/signalr/hubs 引用。应该颠倒过来。另外,jquery 引用是否添加到 _Layout 中?
  • @t4thilina 如果这不起作用,请检查控制台中的任何错误。
  • 感谢您指出这一点。我做了相关的改变。之后它给了我同样的空引用。我通过手动下载“hubs.js”并将其包含在脚本文件夹中来纠正该空问题。它解决了空引用问题,但之后还有更多的复杂情况。所以现在检查一下。
猜你喜欢
  • 1970-01-01
  • 2011-04-17
  • 2021-09-06
  • 2016-12-01
  • 2010-11-29
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多