由于 MVC 如何尝试提供帮助并呈现 jquery 包,我似乎总是遇到这个问题。然后,当您尝试在视图中添加信号器时,它将失败,因为您必须事先添加 jquery,但 jquery 会被 MVC 包再次加载。这会混淆看起来的东西并导致错误。您可能会在主布局页面中有此部分:
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
因此,如果您将脚本添加到脚本部分,它应该会让信号器高兴并且工作正常。
@section scripts {
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.2.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 (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>
}