【发布时间】:2016-03-02 15:46:56
【问题描述】:
我的计划是创建一个简单的聊天网站。我正在使用带有razor 和signalR 的asp.net 网页进行聊天。我已经完成了默认页面和聊天室页面,但我不知道如何“动态”创建聊天室页面的多个实例,以便 /chatroom/1 与 /chatroom/2 是不同的聊天室。 2 instances of chat room page
我假设这可以通过制作 10 个聊天室页面并从 1 到 10 命名它们来完成,但我认为这是不好的做法。我已经完成了路由,以便 /room/[number] 打开聊天室页面的一个实例,但我不知道如何使它们彼此分开。如果需要代码,我可以将其上传到 github。
编辑: Github
路由:
@using System.Web.Routing;
@{
RouteTable.Routes.MapWebPageRoute("{chatroom}/{number}", "~/room.cshtml",
constraints: new { chatroom = "room", number = "[1-9]"});
}
room.cshtml
@{
Layout = "~/_Layout.cshtml";
string s = Request.Url.AbsolutePath;
var RoomNumber = s.Substring(s.LastIndexOf("/") +1);
}
<div id="chat">
<textarea id="chatBox" rows="40" cols="50" readonly="readonly"></textarea>
<input type="text" id="message" placeholder="Your message"/>
<input type="button" id="msgSend" value="Send" />
</div>
<script type="text/javascript">
//simulate msgSend button with enter press when textbox focused
$('#message').bind('keyup', function (e) {
if (e.keyCode === 13) { // 13 is enter key
$('#msgSend').click();
}
});
$(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 (message) {
// Html encode display message.
var encodedMsg = $('<div />').text(message).html();
//get current time
var currentdate = new Date();
var datetime =
+currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
// Add the message to the page.
$('#chatBox').append('\n'+datetime+" "+encodedMsg);
};
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#msgSend').click(function () {
// Call the Send method on the hub.
chat.server.send($('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
【问题讨论】:
-
欢迎来到 StackOverflow!我会说一定要上传代码 - 只需编辑您的问题并添加相关代码,它会让您更容易回答您的问题。
-
问题是,我真的不知道代码的哪一部分是相关的。我什至不知道这整件事是怎么称呼的,因此我无法使用谷歌找到答案。
-
在这种情况下,请提供路由代码和您正在使用的现有聊天室代码 - 太多代码总比没有代码好。
-
已编辑。希望这就是你所要求的。
-
我为我的孩子写了一个聊天应用程序,但我没有使用这种方法。我在后端使用了 ASP.Net、SQL Server 和 ASP.Net Ajax 控件。我没有多个聊天室,但只要让他们选择一个房间号,然后只在表格中显示具有特定房间号的消息,我就可以轻松拥有任意数量的聊天室。您可能想在此处指定 jQuery 作为主标记?
标签: jquery asp.net signalr asp.net-webpages