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.


  1. where to find autogenerated hub script?

  2. Thank you Kumar, it's very usefull for me

  3. Couldn't you have written your own tutorial rather than ripping off

  4. Hello sir i'm newbie, while creating the above application the following error is occurred,

    Error 1 'System.Web.Routing.SignalRRouteExtensions.MapHubs(System.Web.Routing.RouteCollection)' is obsolete: 'Use IAppBuilder.MapSignalR in an Owin Startup class. See for more details.' c:\users\t.sandeep\documents\visual studio 2013\Projects\MvcSignalRApp\MvcSignalRApp\Global.asax.cs 19 13 MvcSignalRApp

    Plz help me out ASAP
    thanks in advance

  5. Prajakta ChaudhariJune 8, 2015 at 4:30 PM

    Nice article. Do you have any example which save data in sql server database?


Post a Comment

Popular posts from this blog

Difference between ViewData, ViewBag and TempData in MVC

While working with ASP.NET MVC applications one need to retain data or need to transfer data from controller to the view or one controller to another controller. In ASP.NET MVC, there are three types of objects - ViewBag, ViewData and TempData, use to pass data from controller to view and controller to controller. Each object has its own functionality, importance and area in which it uses and one needs to decide when to use ViewData, ViewBag or TempData. In this post we’ll look on key points of these three objects.
ViewData: ViewData helps to maintain data when you move from controller to view.
Example: //In Controller defines ViewData FullName. publicActionResult Index() {     ViewData["FullName"] = "Sandeep Kumar"; return View(); } //In View use ViewData @ViewData["FullName"]
Mentioned below are some key points about ViewData: ·ViewData is used to pass data from controller to view. ·ViewData is a dictionary object and is of type ViewDataDictionary. ·Just like any oth…

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

LINQ: Overview of LINQ and it's advantages and disadvantages

Overview of LINQ: LINQ stands for Language Integrated Query, which is descriptive for where it's used and what it does. LINQ is used for querying data. Here I used the generic term "data" and didn't specified type of data. That's because LINQ can be used to query many different types of data, including SQL, XML, and even objects. It is a Microsoft programming model and methodology that gives formal query capabilities into Microsoft .NET-based programming languages (mainly in C# and VB.Net).
LINQ Syntax: LINQ queries can be written through standard query expression or through Lambda expressions.
Query expression syntax:
var items = from item in Items where item.Price > 10 select item;
Lambda expression syntax:
var items = Items.Where(c => c.Price > 10).Select(c => c);
Type of LINQ: Various type of LINQ available is: ·LINQ to SQL ·LINQ to Entities. ·LINQ to Objects ·LINQ to XML ·LINQ to DataSet
AdvantagesandDisadvantages: Mentioned below are advantages an…