Getting Started with ASP.NET MVC, SignalR KnockoutJS

This article describes a simple application intended to notify users when a new user is created. To build the same we are using the technologies like ASP.NET MVC 4, SignalR, KnockoutJS, ToastR, Twitter BootStrap.

First lets create a ASP.NET MVC 4 Web Application. Lets add the SignalR, KnockoutJS, ToastR, Twitter BootStrap by using the Package Manager Console into the project.

install-package knockoutjs
install-package Microsoft.AspNet.SignalR
install-package Twitter.Bootstrap
install-package Toastr

We added a new page "CreateUser.shtml" and the code looks like as shown below

< h2>User Creation
< script src="../../Scripts/jquery-1.9.1.js" type="text/javascript">
    < script src="../../Scripts/knockout-2.3.0.js" type="text/javascript">
< script src="../../Scripts/bootstrap.js" type="text/javascript">
< div class="container-fluid">
    First Name: < input type="text" data-bind="value: firstName" />
        Last Name: < input type="text" data-bind="value: lastName" />
        User Name: < input type="text" data-bind="value: userName" />
        Password: < input type="password" data-bind="value: password" />
        Email Address:< input type="text" data-bind="value: emailAddress" />
          < input class="btn btn-large btn-success" type=" button" id="saveUser" value="Save" />
       
    < ul id="UsersAdded">
    < /ul>
< /div>

< div class="span4">
    First name: < strong data-bind="text: firstName">
    Last name: < strong data-bind="text: lastName">
< /div>

The input class used are the styling defined by the twitter bootstrap.

The screen will look as seen below



We created a new class "UserHub.cs" for the notifying when a new user gets created. The code looks like as
seen below

namespace TestProject.Hubs
{
    public class UserHub : Hub
    {
        public void NotifyUsers()
        {
            Clients.All.addNewUserNotification();
        }
    }
}



Lets create a new "UsersController.cs" under the controllers section and add the below code

 public class UsersController : ApiController
    {
        public string Add(User Name)
        {
            string message = "New User Saved";
            return message;
        }
    }

The above code returns a message that the user is saved.

To auto display the data entered in the text boxes on the labels we would use knockoutJS capability.

The code to bind the values entered in the text boxes for first name and last name to the labels in the second div is as mentioned below

var userModel = {
            firstName: ko.observable(''),
            lastName: ko.observable(''),
            userName: ko.observable(''),
            password: ko.observable(''),
            emailAddress: ko.observable('')
        };
        ko.applyBindings(userModel);

Now lets write the code for the event to be fired when the save is clicked and also for notifying others when
the user is created.

$(function () {
            var user = $.connection.userHub;
            user.client.addNewUserNotification = function () {
             
                $.ajax({
                    url: "/api/users",
                    data: ko.toJSON(userModel),
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    //dataType: "json"
                    success: function (result) {
                        toastr.success(result);
                    }
                });

            };
            $.connection.hub.start().done(function () {
                $('#saveUser').click(function () {
                    user.server.notifyUsers();
                    //$('#message').val('').focus();
                });
            });
        });

In the above code you can see the code to display the confirmation message send by the controller using
toastr javascript notification library as seen below as well

toastr.success(result);

The below code is used for notification of the confirmation message to others using signalR

$.connection.hub.start().done(function () {
                $('#saveUser').click(function () {
                    user.server.notifyUsers();
                    //$('#message').val('').focus();
                });
            });

For demonstration we have opened two browsers, the left hand one we have entered the user information and clicked on save, you can see a notification "New User Saved" and the same notification is send to the right hand browser also also.

Hope this was helpful.

Comments

Popular posts from this blog

Jesus - God Thinks of you.

ASP.NET 4.0 Feature - URL Routing

Tips on JQuery Intellisense in VS 2008