【发布时间】:2013-12-13 05:24:16
【问题描述】:
我遵循这个简单的tutorial 并设法使用signalR 创建了一个测试Web 应用程序。但是当我尝试使用 ASP.NET 网站重新创建它然后浏览 html 页面时,出现以下错误:
TypeError: $.connection is undefined
var chat = $.connection.chatHub;
如果这很重要,这是我的项目的结构:
根据我的发现,在 web.config 中将 runAllManagedModulesForAllRequests 设置为 true 是必要的,所以我已经这样做了。此外,我遵循的教程有点过时,因为我使用仅与 SignalR v 1.1.3 兼容的 VS 2010(即 .NET Framework 4)。
为什么我不能让它在网站上运行,但在网络应用程序中却完美运行?
更新:
一个解决方案(我认为是正确的)建议
将我的代码隐藏文件放在一个单独的 .cs 文件中,然后将该 cs 文件放入 App_Code 文件夹
所以我尝试将我的 html 文件更改为 .aspx 文件。这样我有一个代码隐藏文件(即 .aspx.cs)但我对移动文件隐藏代码的含义感到困惑,因为将我的 .aspx 文件嵌套到 App_Code 文件夹中的 .aspx.cs 文件不是允许。
上面引用的答案是什么意思?
更新:
这是我在 HTMLPage.htm 中的脚本引用以及 main 函数。
<!--Reference the jQuery library. -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.1.3.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 (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + 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.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
【问题讨论】:
-
@LarsHöppner 添加 html 页面是什么意思?
-
@LarsHöppner 我认为这个问题已经解决了here - the second answer by ozgkrc。但似乎我对他到底说了什么一无所知。你能解释一下吗?
-
我认为这个答案在这里不适用——在你的情况下, $.connection 没有定义,这意味着 SignalR 脚本根本没有初始化。这就是为什么我要求提供您正在访问的页面的 HTML - 以查看是否包含相应的 js 文件。
-
@LarsHöppner 我已经包含了可能有帮助的代码。
-
确保没有其他 jQuery 引用 - 另见我的 answer here
标签: c# asp.net visual-studio-2010 signalr