SignalR- Jquery:$ .connection.chathub返回undefined

我正在使用Asp.net MVC,AngularJs,SignalR和Jquery创建一个聊天应用程序。 在聊天视图中,当我尝试设置聊天对象的值时,它传递空值,代码引用位于括号内(var chat = $。connection.chathub;)。 因此,没有其他function可行。 我在这个项目中使用“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")*@      $(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('
You: ' + name + '
'); else { $('#onlineusers').append('
' + name + '
'); $("#users").append('' + name + ''); } }; // chat.client.enters = function (name) { $('#chatlog').append('
' + name + ' joins the conversation
'); $("#users").append('' + name + ''); $('#onlineusers').append('
' + name + '
'); }; // Create a function that the hub can call to broadcast chat messages. chat.client.broadcastMessage = function (name, message) { //display the message $('#chatlog').append('
' + name + ': ' + message + '
'); }; chat.client.disconnected = function (name) { //Calls when someone leaves the page $('#chatlog').append('
' + name + ' leaves the conversation
'); $('#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(); }); }) } }
 @model ZupChatApp.Models.User @{ ViewBag.Title = "ChatRoomView"; } @Html.Label("LoggedInUser", Model.FirstName, new { id = "" }) 

Zup Chat Room View

abcccc
@*
Online Users
*@

您应始终从Microsoft的示例的精确副本开始。 不只是页面而是整个解决方案。 让示例解决方案正常运行。

对于您不熟悉的任何技术都是如此。 然后开始一次修改一件事来达到你的安排。

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

 @section scripts {       } 

    这可能是chathubshell的一个问题。 从“SignalR 2入门” 文档 :

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

    所以,改成它

     var chat = $.connection.chatHub; 

    此外,应在之前添加引用