I want to use SignalR
in my project for real time updates.
My project is developed in WebForms
.
I searched for for 3,4 days but all I found were MVC examples. Can anyone suggest a solution?
You can use SignalR with webforms. See below for an example from the tutorial here
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>
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();
}
Add SignalR packages via NuGet. (Trying searching for "Microsoft ASP.Net SignalR JS" and "Microsoft ASP.Net SignalR JS")
Create a Hub class
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));
}
}
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>
Add the following to the Application_Start event handler in global.asax.cs
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}