Skip to main content

SignalR Tutorial: Your first SignalR chat application with MVC 4

In last post I explained what SignalR, why do us need it is and what are the prerequisites.

In this tutorial we’ll use ASP.NET SignalR to create a real-time chat application.

First of all we’ll add SignalR library to an MVC 4 application and then create hub class (to push content to client) and after that we’ll use SignalR jQuery library to send messages and display updates from the hub.

·         Open Visual Studio -> Select ASP.NET MVC4 Web Application template (under Web Templates) and enter the name of application as “MVCSignalRApp” and then click OK.

·         On the next screen select “Internet Application” template and then click OK.

·         Your basic MVC application is ready to use, now we need to add SignalR libraries to this application. To add SignalR libraries open Package Manager Console (TOOLS - >Library Package Manager -> Package Manager Console) and then run following command.

install-package Microsoft.AspNet.SignalR

·         It’ll add all the required SignalR libraries to our application. For instance you can check SignalR JavaScript files under Script folder. Application references are also updated in our application.

·         In Solution Explorer, right-click on the project, select Add -> New Folder, and name the new folder as “SignalRHub”.

·         Under this folder Add a new class and give it a name as “ChatHub.cs” and replace the code of this class with the following code:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace MvcSignalRApp.SignalRHub
    public class ChatHub : Hub
        public void Send(string name, string message)
            // Call the 'addNewMessageToPage' method to update clients.
            Clients.All.addNewMessageToPage(name, message);

Understand the code of ChatHub class:

§        In the above code the ChatHub class derives from the Hub (under Microsoft.AspNet.SignalR namespace) class. Deriving from the Hub class is a useful way to build a SignalR application.
§        We can create public methods in hub class and then we can access those methods by calling them from jQuery scripts in a web page. In this case we have defined one public method “Send”; clients call the ChatHub.Send method to send a new message. In the “send” method jQuery “addNewMessageToPage“(through “Clients.All”) method is called through which the hub sends the message to all clients.
§        In the “addNewMessageToPage” method display name of user and message entered by user is sent to browser to display for all other clients.

·         Open the Global.asax file and add a call to the method RouteTable.Routes.MapHubs() in the “Application_Start” method to register the default route for SignalR hubs. This code must be called before you register any other routes through Global.asax.

protected void Application_Start()
    // Register the default hubs route: ~/signalr/hubs


·         Open the Controllers -> HomeController.cs and add the “ChatApp” method to the class. This method returns the ChatApp view that we’ll create in a later step.

public ActionResult ChatApp()
    return View();

·         Right-click on the ChatApp method you just created, and click Add View to create a new view file.

·         On the next screen give your view a name and mark the “Use a layout or master page” checkbox to check and click on Add.

·         Open the view file ChatApp.cshtml. And After the <h2> tag, paste the mentioned below <div> section and @section scripts code block into the page. This script enables the page to send chat messages and display messages from the server.

<div class="container">
        <label id="userName" style="display: inline;"></label>
    <input type="text" id="messageBox" />
    <input type="button" id="sendMessage" value="Send" />
    <ul id="messageList" style="list-style: none; padding-left: 0px;">

@section scripts {
    <!--Script references. -->
    <!--The jQuery library are referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>

    <!--SignalR script to update the ChatApp page and send messages.-->
        $(function () {

            // Reference the auto-generated proxy for the hub. 
            var chat = $.connection.chatHub;

            // Create a function that the hub can call back
            // to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the user message to the page.
                    + encodeHtml(name) + '</strong>: '
                    + encodeHtml(message) + '</li>');

            // Get the user name and store it to prepend to messages.
            $('#userName').text(prompt('Enter your name:', ''));

            // Set initial focus to message input box. 

            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendMessage').click(function () {
                    // Call the Send method on the hub.
                        , $('#messageBox').val());
                    // Clear text box and reset focus for next comment.

        // This optional function html-encodes messages
        // for display in the page.
        function encodeHtml(value) {
            var ecValue = $('<div />').text(value).html();
            return ecValue;

“Comments have been added to code for better understanding, however please make sure that the script references in your code match the versions of the script libraries installed in your project as VS Package manager might install most recent versions of the scripts than the versions shown in this post.”

·         Save all of your work and then press F5 to see our SignalR chat application in action.

·         By default you’ll see home screen of application, I have added Chat link (on top right corner after Contact link) to navigate user to chat page. Click on this link to open chat.

·         Once you navigate to the chat page, it’ll ask for your name that will display against your chat messages, enter the name and click OK.

·         Open this page in different browser and same way enter the name, so now we have two users ready for real time chat.

·         Enter the message from any of the browser window and you can see that message in both windows against the display name of user.

This sample chat application does not maintain discussion context on the server and user cannot see the old messages.


In this tutorial we have learned:
·         How to add SignalR libraries to an ASP.NET MVC 4 application
·         Create and use the hub class.
·         Register the default route for SignalR hubs.
·         Send and receive messages from the hub

You can download the source code of this sample for reference.

That’s it for now, hope you have enjoyed learning SignalR; it’s an awesome framework to create real-time, multi-user interactive web applications.

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI.
Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress).
//Created new Workbook var hwb = new NPOI.HSSF.UserModel.HSSFWorkbook(); //Create worksheet with name. var sheet = hwb.CreateSheet("new sheet"); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue("This is Merged cell"); cell.CellStyle.WrapText = true; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra);
Hope this solution helps you J

Calculate Sum and average of two or more Textbox values using JQuery

We can calculate sum and average of values entered in textboxes with the help of small piece of jQuery code.
First of all let’s create a HTML form where we’ll ask user to enter marks in each subject, under body section add following HTML:
<tableclass="demo-table"> <trclass="label"> <tdcolspan="2">Please enter marks(0-99):</td> </tr> <tr> <td>English</td> <td> <inputtype="text"class="txtMarks"name="txtMarks"

Difference between Web API, WCF and Web Service

So now we have got the basic idea about Web API, now let’s do some comparison of Web API with WCF and web services.
Web Service WCF Web API Web services created as file with .asmx extension. WCF create with .svc extension Web API are simple class file with .cs(for C#) extension. Web API is inherited from “ApiController” and class name must end with “Controller”. It is SOAP based service and return data in XML form. It is also based on SOAP and return data in XML form. Web API is HTTP based service and by default it return data in JSON or XML form. It supports only HTTP protocol. It supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. It supports HTTP protocol. It can be hosted only on IIS. It can be hosted with in the application or on IIS or using window service. It can be hosted with in the application or on IIS. It is not open source but can be consumed by any client that understands xml. It is not open source but can be consumed by any client t…