一直在努力解决这个错误贴两个小时..
TypeError: $.connection is undefined [Break On This Error] var chatHubClient = $.connection.chatHub;
这是我的Chat.cs(在控制器文件夹中 – 我猜这是我做错了,但我找不到任何关于放置它或如何路由它的文档)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using SignalR.Hubs; namespace SingalrTest.Controllers { public class Chat { private readonly static Lazy<Chat> _instance = new Lazy<Chat>(() => new Chat()); public static Chat Instance { get { return _instance.Value; } } } [HubName("chatHub")] public class ChatHub : Hub { private readonly int TimeoutInSeconds = 30; private readonly Chat _chat; public ChatHub() : this(Chat.Instance) { } private ChatHub(Chat chat) { this._chat = chat; } public void Join(string channelName) { System.Diagnostics.Debug.WriteLine("Someone joined " + channelName); } } }
最后,..可能_Layout.cs.html
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="utf-8" /> <title>@ViewBag.Title - My ASP.NET MVC Application</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <Meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/Scripts/jquery-1.8.1.js") @Scripts.Render("~/Scripts/jquery.signalR-0.5.3.js") @Scripts.Render("~/signalr/hubs") <script type="text/javascript"> $(document).ready(function () { // var chatHubClient = jQuery.connection.chatHub; var chatHubClient = $.connection.chatHub; $.connection.chatHub.start(function () { chatHubClient.join('TEST'); }); }); </script> </head> <body> ... </body> </html>
如果我访问/ signalr / hubs,我可以看到源是正确生成的.那么我想念的是什么?
解决方法
你可能已经开始……
但这是解决方案.
你在head标签中以正确的顺序拥有所有脚本.但是Visual Studio模板中的_Layout.cshtml在body标记的末尾有以下行.
@Scripts.Render("~/bundles/jquery") @RenderSection("scripts",required: false)
这个bundle有jQuery库,它在加载时会覆盖$object.因此,SignalR在此设置上的任何“内容”现在都会被覆盖,无法访问.
@section scripts { @* Load your scripts here. (and remove jQuery,coz it's already loaded) *@ }
希望这可以帮助.