Been struggling with this error the paste two hours..
TypeError: $.connection is undefined
[Break On This Error]
var chatHubClient = $.connection.chatHub;
here is my Chat.cs (which is in the controller folder - my guess is this is what I'm doing wrong, but I can't find any documentation on where to put it or how to route it)
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);
}
}
}
And at last,.. the might _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>
And if I visit the /signalr/hubs I can see that the source is generated correctly. So what biggy am I missing?
you may have moved on...
But here's the solution.
you have all your scripts in the right order in the head tag. But the _Layout.cshtml
from the Visual Studio template has following lines at the end of the body tag.
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
This bundle has the jQuery library, which overwrites the $ object when it loads. So any 'stuff' on this setup by SignalR are now overwritten and are not accessible.
simply use following in your page.
@section scripts {
@* Load your scripts here. (and remove jQuery, coz it's already loaded) *@
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With