Technology

Building an Online Chat Application – ASP.NET MVC, jQuery, and AJAX


For this month’s IndyNDA ASP.NET SIG, I showcased an example web app that shows off the AJAX power of jQuery and the AJAX-response goodness built into ASP.NET MVC.

The basic premise is that we want to have a website that has a live chat on the homepage.  Users can log in and then post new messages to that chat.  We do not want any model (data) binding on the server, we want jQuery to ask the server for the data and then post that data on the website.  Also we want jQuery to send new messages sent by a user to the server using AJAX as well.

SIMPLE!  Here we go….

Getting Started

You might have seen from some of my earlier prototyping posts that the biggest hurtle to get through when trying to create a new web app is spending too much time on the “look” of the site.  I am just as guilty as the next guy of spending 3 hours on the padding, margin, and color of a box just to get it to “look just right.”  In this project we just want to get straight to the coding of the AJAX and MVC goodness.  My suggestion is to go get on Google and just search for “free html templates”.  You will have a ton of options.  Just pick one that looks good.  For the downloadable project at the end of this post, I chose the “Emporium” template from FreeLayouts.com.

In Visual Studio you will want to create a new “ASP.NET MVC 2 Empty Web Application” project.  To incorporate that template into a new MVC project, just copy the CSS and image folders into the “Content” folder of your project.  You will need to create a new master page in the “Shared” folder and then the copy and paste the relative parts of the HTML template over to the master page.  Be sure to create the title (name the ID “TitleContent”), header (name the ID “HeaderContent”), and main content (name the ID “MainContent”) areas.

Because we started with a blank project you will need to create a “HomeController” in the “Controller” folder.  You can open that class up, right click on the “Index” action method already created, select “Add View…”, and just use the default settings.

Go ahead and hit F5 in Visual Studio and you should see just the template show up.  Now we can get into the AJAX goodness!

Client Side

The client side of our application will utilize jQuery to send and receive messages from the server.  jQuery works with the DOM and the HTML objects on the page for the data from the server.  We will have three specific objects that will either give or receive information from jQuery.  We will have a text box and button that will serve as the way a user submits new messages to the chat.  We will have a header tag for status messages as jQuery sends and receives information to the server.  And finally we will have a div chat area that will get set with all the messages to be displayed on the screen.

Below is the new message area:

<p>
<input type="hidden" id="newmessage_username" value="SOME USERNAME" />
Message<br />
<input type="text" id="newmessage_messagebody" size="70" />
<input type="button" value="Send" id="newmessage_sendbutton" onclick="sendNewMessage()" />
</p>

Below is the status message and chat area

<h2>Chat</h2>
<h4 id="message"></h4>
<div id="chatarea">
</div>

To handle both of these areas, we need one function to send data to the server (submit new message) and we need a function to get data (list of new messages for the chat area.)

The key to the client side here is to have unique ID’s for each of the items we want to update with jQuery.  In jQuery we can reference those items by typing $(“#ID_OF_ITEM”).

Below is a function that runs when the website loads.  It sets up a time-based loop that will call a function to update the chat messages.  Basically messages will reload every 5 seconds.

$(document).ready(function () {
    $("#message").html("Waiting for update...");
    var refreshId = setInterval(
        "updateChatArea()",
        5000);
});

Below we have the function to get data from the server.  We are using the getJSON AJAX function built into jQuery.  We will call the webpage “/Home/GetMessage/” (or in MVC speak we call the GetMessage action method in the Home controller.)  The page will return “data” which will be passed to a function.  We update the status message at different times to give the user some feedback that stuff is happening.  We then just loop through the data and inject those messages into the chat area.

function updateChatArea() {
    $.getJSON(
       "/Home/GetMessages/",
        null,
        function (data) {
            $("#message").html += "Fetching...";
            $("#chatarea").html("");
            var x;
            if (data.length > 0) {
                for (x in data) {
                    $("#chatarea").html(
                    $("#chatarea").html() +
                    "<p><b>" +
                    data[x].Username + "</b> <i>(" +
                    data[x].PostDateTime + ")</i> - " +
                    data[x].MessageBody + "</p>");
                }
            }
            else {
                $("#chatarea").html("<p>No Messages</p>");
            }
        });
    $("#message").html("Messages loaded.");
}

Below is the function that will send a new message to the server.  Basically we are sending JSON object (with two key/value pairs: username and messagebody) to “/Home/AddMessage” (or again to the AddMessage action method in the Home controller.)  We are using jQuery to get the information from a hidden username field that was set by the server when the page was created and by a message text box.)

function sendNewMessage() {
    $.post(
        "/Home/AddMessage",
        {
            Username: $("#newmessage_username").val(),
            MessageBody: $("#newmessage_messagebody").val()
        });
    $("#newmessage_messagebody").val("");
    updateChatArea();
}

That pretty much wraps up the basic client side code.  Let’s take a look at how the server will interact with the client.

Server Side

The server side is very simple.  ASP.NET MVC has many built in features that allow you to interact with client side requests. 

For setup we do have a simple mock user authentication system setup to allow multiple users to log into the system.  Check that out by downloading the full project.

To store the messages, I have created a simple Entity Framework project that has a single entity, “Message”.  To create the same setup you will need to perform three steps after downloading the project.

  1. Create a new database in SQL Server named “OnlineChat”.
  2. Modify the connection string in the web.config file named “OnlineChatEntities” with the settings for your development machine.  Look for and replace the YOUR_SQL_SERVER_NAME and the YOUR_SQL_DATABASE_NAME areas in the connection string. 
  3. Open the OnlineChat.edmx file right-click in the design view and select “Generate Database from Model…”  Go through the steps and it should generate the Message table in the database and setup the connection between the Entity framework and your database.

Now looking at the Home controller and responding to those requests from jQuery.

Below is the code for the GetMessage function that is called to get the messages to be placed in the chat area.  This has some pretty simple code.  It queries the data source for 10 messages ordered by their post dates in new first order.  It then adds each of these messages to a LinkedList.  Each of the Message objects are actually moved into anonymous objects inside the LinkedList.

The unique thing about this method is the result it sends.  It uses the built-in MVC type of JsonResult.  This will return in the Javascript-native JSON format.  On top of which we use the Json() method that will serialize the LinkedList (and its objects) into a JSON result.

public JsonResult GetMessages()
{
    OnlineChatEntities chatEntities = new OnlineChatEntities();
    var messages = chatEntities.Messages
                               .OrderByDescending(x => x.PostDateTime)
                               .Take(10);
    var result = new LinkedList<object>();
    foreach (var message in messages)
    {
        result.AddLast(new {
                            Username = message.Username,
                            PostDateTime = message.PostDateTime.ToString(),
                            MessageBody = message.MessageBody });
    }
    return Json(result, JsonRequestBehavior.AllowGet);
}

Below is the GetMessage action method that will receive a new message to be placed in the chat.  If we look at what is sent, we know that jQuery is sending a JSON object that just contains a username and messagebody key/value pair.  We can actually setup a ViewModel class that matches that layout and MVC will automatically bind incoming JSON data to a new C# object.  We then take that new object and insert it into the database (using EF).  We create an anonymous object and then return it the same way we did for the GetMessage method.  Here we are sending a message of success.  On the jQuery side you can use these return messages to error check the sending of a message.

public JsonResult AddMessage(NewMessageViewModel message)
{
    Message newMessage = new Message();
    newMessage.Username = message.Username;
    newMessage.MessageBody = message.MessageBody;
    newMessage.PostDateTime = DateTime.Now;

    OnlineChatEntities chatEntities = new OnlineChatEntities();
    chatEntities.Messages.AddObject(newMessage);
    chatEntities.SaveChanges();
    var result = new { message = "Success" };
    return Json(result, JsonRequestBehavior.AllowGet);
}

To see the full project and have all the code available, please download the ZIP file containing the solution and all the code below.

OnlineChatAJAX [Download]

Taking it a step further…

After you dig a little deeper in the code you will find an unfinished section in the sidebar of the website.  This is a section that shows all the users currently online and chatting on the website.  This is where you can create the jQuery/AJAX/MVC code and get your hands dirty.

How would you use jQuery and MVC to create a live online user list in the sidebar?  Can you use the same concepts as the GetMessages functions to create a GetUsers?  How will you know a user is still online?  What if they closed their browser or moved to another website? How will you know?

Here is a couple of tips… you will have to move the user authentication into the database (the current project has hard-coded users in mock repositories.)  You will need to have code to check-in a user after a certain time.  And if a user does not check in after a certain time, you can count that person as not online.

Have fun and just keep coding… just keep coding… just keep coding, coding, coding… what do we do, we code, code.

Uncategorized
Personal Hedgehog?
Business
Do you Scrum?
  • walwal

    Author Reply

    Thanks mate, an interesting read


  • baharbahar

    Author Reply

    hi
    thanks a lot.
    please help me: I want to have chat between tow person similar too gmail I mean each tow comunication in new window
    how do i separate comunication between tow person plz help me
    thanks


  • bahar,
    Thanks for commenting. This post is was just meant to be a starting point to create an online chat function. To accomplish what you need, two person communication, you will need to incorporate user authentication into the chat. Then each message is associated with the user that sent it. You would not be limited to just two people. You could make this more into a chat room environment by allowing multiple people to chat on the same session.


  • Excellent post. I used to be checking continuously this blog and I am impressed! Very helpful information specially the last phase 🙂 I take care of such information much. I used to be looking for this certain info for a long time. Thank you and good luck.


  • JamesJames

    Author Reply

    Thanks, this is the only simple MVC chat that’s easy to follow without any headache .

    Thanks once again

    you on quora?


  • I want to make facebook like chat system so what should i do so a individual user can talk his individual friend and also multiuser friends pls guide me i m a it student and have an project of developing chat website.