【发布时间】:2025-12-13 23:35:01
【问题描述】:
我正在尝试在我的 ASP.NET 解决方案上创建用户之间的聊天应用程序。安装 SignalR 以帮助进行实时聊天。但是,使用 JavaScript 创建的按钮没有触发,浏览器也没有按预期提示输入用户名。
下面是我的代码。 Check out the design here
C# 代码隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace Synergince
{
// This is a class to handle the username and message entered by the username
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcast method to update clients
Clients.All.broadcastMessage(name, message);
}
}
}
源代码 - JavaScript
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden"id="displayname" />
<ul id="discussion">
</ul>
</div>
<!--Script references -->
<script src="Scripts/jquery-1.4.1.min.js"></script>
<script src="Scripts/jquery.signalR-1.2.1.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript"">
$(on('click',function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
var Name = $('<div />').text(name).html();
var Msg = $('<div />').text(message).html();
//add message to the page
$('#discussion').append('<li><strong>' + encodedName + '</strong>: ' + encodeMsg + '</li>');
};
//get username from user
$('#displayname').val(prompt('Enter preferred alias:', ''));
$('#message').focus();
//start connection
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
//call send method on the hub
chat.server.send($('#displayname').val(), $('#message').val());
//clear textbox
$('#message').val('').focus();
});
});
});
</script>
【问题讨论】:
标签: javascript c# jquery asp.net signalr