Step-10: Create an MVC Controller
Add a new Controller named "HomeController.cs"
Step-11: Add new action into your controller.
Here I have added "Index" Action into "Home" Controller.
public ActionResult Index()
{
return View();
}
Step-12: Add view for your Action named "Index.cshtml"
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<a target="_blank" href="Add/">Add
Employe</a>
Step-13: Add another action in HomeController tofetch Employee data.
public JsonResult GetNotifications()
{
var notificationRegisterTime = Session["LastUpdated"] != null ? Convert.ToDateTime(Session["LastUpdated"]) : DateTime.Now;
NotificationComponent NC = new NotificationComponent();
var list = NC.GetData(notificationRegisterTime);
//update session here for get only new added contacts (notification)
Session["LastUpdate"] = DateTime.Now;
return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Step-14: Add and update _Layout.cshtml for showing notification.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - MY SignalR Demo</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<span class="noti glyphicon glyphicon-bell"><span class="count"> </span></span>
<div class="noti-content">
<div class="noti-top-arrow"></div>
<ul id="notiContent"></ul>
</div>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("SignalR Demo", "Index", "Home", null, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My SignalR Demo</p>
</footer>
</div>
@* Add Jquery Library *@
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
@* Add css *@
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
/*Added css for design notification area, you can design by your self*/
/* COPY css content from youtube video description*/
.noti-content{
position:fixed;
right:100px;
background:#e5e5e5;
border-radius:4px;
top:47px;
width:250px;
display:none;
border: 1px solid #9E988B;
}
ul#notiContent{
max-height:200px;
overflow:auto;
padding:0px;
margin:0px;
padding-left:20px;
}
ul#notiContent li {
margin:3px;
padding:6px;
background:#fff;
}
.noti-top-arrow{
border-color:transparent;
border-bottom-color:#F5DEB3;
border-style:dashed dashed solid;
border-width: 0 8.5px 8.5px;
position:absolute;
right:32px;
top:-8px;
}
span.noti{
color:#FF2323;
margin:15px;
position:fixed;
right:100px;
font-size:18px;
cursor:pointer;
}
span.count{
position:relative;
top:-3px;
}
</style>
@* Add jquery code for Get Notification & setup signalr *@
<script type="text/javascript">
$(function () {
// Click on notification icon for show notification
$('span.noti').click(function (e) {
debugger;
e.stopPropagation();
$('.noti-content').show();
var count = 0;
count = parseInt($('span.count').html()) || 0;
//only load notification if not already loaded
if (count > 0) {
updateNotification();
}
$('span.count', this).html(' ');
})
// hide notifications
$('html').click(function () {
$('.noti-content').hide();
})
// update notification
function updateNotification() {
$('#notiContent').empty();
$('#notiContent').append($('<li>Loading...</li>'));
$.ajax({
type: 'GET',
url: '/home/GetNotifications',
success: function (response) {
debugger;
$('#notiContent').empty();
if (response.length == 0) {
$('#notiContent').append($('<li>No data available</li>'));
}
$.each(response, function (index, value) {
$('#notiContent').append($('<li>New contact : ' + value.Name + ' (' + value.ID + ') added</li>'));
});
},
error: function (error) {
console.log(error);
}
})
}
// update notification count
function updateNotificationCount() {
var count = 0;
count = parseInt($('span.count').html()) || 0;
count++;
$('span.count').html(count);
}
// signalr js code for start hub and send receive notification
var notificationHub = $.connection.notificationHub;
$.connection.hub.start().done(function () {
console.log('Notification hub started');
});
//signalr method for push server message to client
notificationHub.client.notify = function (message) {
if (message && message.toLowerCase() == "added") {
updateNotificationCount();
}
}
})
</script>
</body>
</html>
Step-15: Update global.asax.cs to start, stop SQL dependency
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace SignalRDemo
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// WebApiConfig.Register(GlobalConfiguration.Configuration);
// FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//here in Application Start we will start Sql Dependency
SqlDependency.Start(con);
}
protected void Session_Start(object sender, EventArgs e)
{
NotificationComponent NC = new NotificationComponent();
var currentTime = DateTime.Now;
HttpContext.Current.Session["LastUpdated"] = currentTime;
NC.RegisterNotification(currentTime);
}
protected void Application_End()
{
//here we will stop Sql Dependency
SqlDependency.Stop(con);
}
}
}
Step-16: Run Application.
Step-17: Now add a new Controller/Action To add Employee Data.
1- I have created AddController.cs in Controller directory.
2- Add action named "Index"
public ActionResult Index()
{
return View();
}
3- Create View for Index action to add Employee
@model SignalRDemo.tblEmployee
@{
ViewBag.Title = "Index";
}
<h2>Add Employee</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Add Employee</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
4- Add Post action for Index and add code to insert Employee
[HttpPost]
public ActionResult Index(tblEmployee model)
{
SignalRDBEntities entity = new SignalRDBEntities();
model.AddedOn = DateTime.Now;
entity.tblEmployees.Add(model);
entity.SaveChanges();
return View();
}
Step-18: Run Application.
Click On Add Employee Link. it will open a new Page.
Type Name in textbox and click on Create button.it saves data in the table. Now go to first tab to see notification.
Click here to download this project
Download
Like and share if you liked this post.
Thanks-