SignalR 可以与 asp.net WebForms 一起使用吗? [英] Can SignalR be used with asp.net WebForms?
问题描述
我想在我的项目中使用 SignalR
进行实时更新.
I want to use SignalR
in my project for real time updates.
我的项目是在 WebForms
中开发的.
My project is developed in WebForms
.
我搜索了 3,4 天,但我找到的都是 MVC 示例.任何人都可以提出解决方案吗?
I searched for for 3,4 days but all I found were MVC examples. Can anyone suggest a solution?
推荐答案
您可以将 SignalR 与网络表单一起使用.请参阅下面的教程示例 此处
You can use SignalR with webforms. See below for an example from the tutorial here
针对 .NET Framework 4.5 或更高版本创建一个新的 ASP.NET WebForms 项目
Create a new ASP.NET WebForms project targeting .NET Framework 4.5 or later
更改主页以包含以下内容
Change the home page to contain the following
<asp:content runat="server" id="BodyContent" contentplaceholderid="MainContent">
<h3>Log Items</h3>
<asp:listview id="logListView" runat="server" itemplaceholderid="itemPlaceHolder" clientidmode="Static" enableviewstate="false">
<layouttemplate>
<ul id="logUl">
<li runat="server" id="itemPlaceHolder"></li>
</ul>
</layouttemplate>
<itemtemplate>
<li><span class="logItem"><%#Container.DataItem.ToString() %></span></li>
</itemtemplate>
</asp:listview>
</asp:content>
编辑 default.aspx.cs 代码隐藏文件以包含以下事件
Edit the default.aspx.cs codebehind file to include the following event
protected void Page_Load(object sender, EventArgs e)
{
var myLog = new List<string>();
myLog.Add(string.Format("{0} - Logging Started", DateTime.UtcNow));
logListView.DataSource = myLog;
logListView.DataBind();
}
通过 NuGet 添加 SignalR 包.(尝试搜索Microsoft ASP.Net SignalR JS"和Microsoft ASP.Net SignalR JS")
Add SignalR packages via NuGet. (Trying searching for "Microsoft ASP.Net SignalR JS" and "Microsoft ASP.Net SignalR JS")
创建 Hub 类
public class LogHub : Hub
{
public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();
static LogHub()
{
_Timer.Interval = 2000;
_Timer.Elapsed += TimerElapsed;
_Timer.Start();
}
static void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
var hub = GlobalHost.ConnectionManager.GetHubContext("LogHub");
hub.Clients.All.logMessage(string.Format("{0} - Still running", DateTime.UtcNow));
}
}
在页面底部设置以下脚本块(您的 jquery 和 jquery.signalr 版本可能不同)
Setup the following script block at the bottom of your page (your jquery and jquery.signalr version may vary)
<script src="Scripts/jquery.1.7.1.min.js"></script>
<script src="Scripts/jquery.signalR-1.0.0-rc1.min.js"></script>
<script src="http://www.codeproject.com/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var logger = $.connection.logHub;
logger.client.logMessage = function(msg) {
$("#logUl").append("<li>" + msg + "</li>");
};
$.connection.hub.start();
});
</script>
将以下内容添加到 global.asax.cs 中的 Application_Start 事件处理程序
Add the following to the Application_Start event handler in global.asax.cs
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
这篇关于SignalR 可以与 asp.net WebForms 一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!