我的计划是创建一个简单的聊天网站。我正在使用带有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>