Click here to Skip to main content
15,886,071 members
Articles / All Topics

Broadcasting Website Data using SignalR in MVC

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
21 Dec 2015CPOL3 min read 10K   7   1
How to broadcast website data using SignalR in MVC

SignalR is a cool API in .NET Framework which you can use to show real time data in your application. You can broadcast real time data to all the connected clients(browsers) once data is ready on server side.

It generates JavaScripts when rendering on the client side. But you don’t have to worry about all the proxy JavaScripts as signalR takes care of all those things. All you have to do is just call your JavaScript function from the server side.

To add signalR in your project, go to Nuget Package Manager and search for signalR, you will see Microsoft ASP.NET SignalR at the top of the list, just click install. It will add all the references required to run it. If your project doesn’t have a Scripts folder, it will add a Scripts folder and import jquery and jquery-signalR libraries.

At this stage, you’ve got all the required references and scripts. Now, it's time to add the SignalR startup class so we can tell the OWIN so it can configure it.

Startup class is like:

C#
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(DeepASP.SignalRMVC.SignalRStartup))]
namespace DeepASP.SignalRMVC
{
public partial class SignalRStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

I added this startup class in App_Start folder as MVC has already created this folder with the startup classes. But you can keep wherever you want. Now add the SignalR Hub class. If you right click and add new item, it should be under signalR templates but if it is not, don’t worry, just add a new class and inherit it from abstract class:

C#
Microsoft.AspNet.SignalR.Hub

Let's name this class as “SignalRHub”. You can name anything, but just remember this is the hub which you will use in the JavaScript side. Although you can change the display name by decorating this class with attribute:

C#
[Microsoft.AspNet.SignalR.Hubs.HubName("DisplayName")].

This class looks like:

C#
namespace DeepASP.SignalRMVC
{
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
[HubName("Broadcaster")]
public class SignalRHub : Hub
{ }
}

Logically, that’s all you needed for signalR. Now you want to access the Hub so you can call JavaScript function from server side, right? YES. OK, let's add another class Broadcast.cs as:

C#
namespace DeepASP.SignalRMVC
{
    using Microsoft.AspNet.SignalR;
    using System;

    public class Broadcast
    {
        private static Lazy<ihubcontext> context = 
		new Lazy<ihubcontext>(() =>
		GlobalHost.ConnectionManager.GetHubContext<signalrhub>());

        private static IHubContext Broadcaster
        {
            get
            {
                return context.Value;
            }
        }

        public static bool SendDataToAllConnectedClients(string data)
        {
            Broadcaster.Clients.All.JavaScriptFunction(data);
            return true;
        }
    }
}</signalrhub></ihubcontext></ihubcontext>

SendDataToAllConnectedClients method calls JavaScript function “JavaScriptFunction” passing a string parameter. You can pass as many complex objects in JSON format as you want. Just for clarity, I call the JavaScript side function name as JavascriptFunction but you will give a meaningful and purposeful name. Now, we will write this JavaScript function. Like for this post, I created another controller called BroadcastController.cs and its view. Now because this view will be responsible for broadcasting the message sent from server, we will add the required .js libraries in this view:

JavaScript
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/signalr/hubs"></script>
<script>
    var broadcaster = $.connection.Broadcaster;
    broadcaster.client.JavaScriptFunction = function (d) {
        document.getElementById("data").innerHTML = d;
    }
    $.connection.hub.start();
</script>

Order of JavaScript libraries DOES matter. Now this is where we are subscribing the JavaScript function “JavaScriptFunction” which we are calling from server side. For this demo, I was just sending a string html from server side, but you can write your logic for this function here when you are subscribing.

Yep, that’s all signalR is about. If you are interested in downloading this demo, just click here.

Well, here are some important things to remember before you going to move into production.

Pre-requisites of SignalR2

  • .NET Framework 4.5
  • The user for which application (IIS) is running must have full trust
  • IIS must be running in Managed mode NOT Classic
  • IIS 7 or greater (Websocket requires IIS8)
  • jQuery version must be greater than 1.6

If you want more control on server side, then you might want to look into this http://socket.io/docs/.

Well, here are some of the cool articles I came across while researching some of the issues when I was working on my signalR project:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
My name is Muhammad Hussain. I'm a Software Engineer.
blog

Comments and Discussions

 
GeneralMy vote of 5 Pin
Santhakumar M22-Dec-15 4:04
professionalSanthakumar M22-Dec-15 4:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.