CRUD Operation In ASP.NET MVC Razor Using SignalR And Entity Framework

SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications.

Introduction

SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to make the Server code push the content to connected clients instantly as it becomes available, rather than having the Server wait for a client to request the new data.

Description

SignalR can be used to add any sort of "real-time" web functionality to your MVC application. While Chat is often used as an example, you can do a whole lot more; examples include dashboards and monitoring applications, collaborative applications such as simultaneous editing of documents, job progress updates, and real-time forms. We must have a way to notify all the connected clients if there are any changes on the Server, without a refresh or update the web page. This is the scenario in which ASP.NET SignalR comes handy.

Here, I make Views to insert, update, and delete records. If the user makes some changes in one browser like insert, update, or delete, then the same effect will be shown in another browser without reloading the pages. This process is called asynchronous.
 
 Link to the source code - Click Here>>
 
Steps to be followed -

Step 1

Create an MVC application named "SatyaprakashMVCsignalRCrud".
 
 
Step 2

Create a table named "Customers".

SQL Script
  1. SET ANSI_NULLS ON  
  2. GO  
  3.   
  4. SET QUOTED_IDENTIFIER ON  
  5. GO  
  6.   
  7. SET ANSI_PADDING OFF  
  8. GO  
  9.   
  10. CREATE TABLE [dbo].[Customers](  
  11.     [Id] [bigint] IDENTITY(1,1) NOT NULL,  
  12.     [CustName] [varchar](100) NULL,  
  13.     [CustEmail] [varchar](150) NULL,  
  14.  CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED   
  15. (  
  16.     [Id] ASC  
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)   
  18.   
  19. ON [PRIMARY]  
  20. ON [PRIMARY]  
  21.   
  22. GO  
  23.   
  24. SET ANSI_PADDING OFF  
  25. GO  
Step 3

Then, create a list of procedures as in the attached file named "StoredProcedureLists.zip". 
 
Step 4

I have created a Controller class file named "HomeController.cs".

Description
 
Get Data
  1. [HttpGet]  
  2.        public ActionResult GetAllData()  
  3.        {  
  4.            int Count = 10; IEnumerable<object> Result = null;  
  5.            try  
  6.            {  
  7.                object[] parameters = { Count };  
  8.                Result = objCust.GetAll(parameters);  
  9.   
  10.            }  
  11.            catch { }  
  12.            return PartialView("_DataList", Result);  
  13.        } 
Insert data
  1. [HttpPost]  
  2.         public ActionResult Insert(Customer model)  
  3.         {  
  4.             int result = 0;  
  5.             try  
  6.             {  
  7.                 if (ModelState.IsValid)  
  8.                 {  
  9.                     object[] parameters = { model.CustName, model.CustEmail };  
  10.                     result = objCust.Insert(parameters);  
  11.                     if (result == 1)  
  12.                     {  
  13.                         //Notify to all  
  14.                         CustomerHub.BroadcastData();  
  15.                     }  
  16.                 }  
  17.             }  
  18.             catch { }  
  19.             return View("Index");  
  20.         } 
Delete data
  1. public ActionResult Delete(int id)  
  2.        {  
  3.            int result = 0;  
  4.            try  
  5.            {  
  6.                object[] parameters = { id };  
  7.                result = objCust.Delete(parameters);  
  8.                if (result == 1)  
  9.                {  
  10.                    //Notify to all  
  11.                    CustomerHub.BroadcastData();  
  12.                }  
  13.            }  
  14.            catch { }  
  15.            return View("Index");  
  16.        } 
Update data
  1. [HttpPost]  
  2.         public ActionResult Update(Customer model)  
  3.         {  
  4.             int result = 0;  
  5.             try  
  6.             {  
  7.                 object[] parameters = { model.Id, model.CustName, model.CustEmail };  
  8.                 result = objCust.Update(parameters);  
  9.   
  10.                 if (result == 1)  
  11.                 {  
  12.                     //Notify to all  
  13.                     CustomerHub.BroadcastData();  
  14.                 }  
  15.             }  
  16.             catch { }  
  17.             return View("Index");  
  18.         } 
To get the data for updation purpose by taking ID
  1. public ActionResult Update(int id)  
  2.         {  
  3.             object result = null;  
  4.             try  
  5.             {  
  6.                 object[] parameters = { id };  
  7.                 result = this.objCust.GetbyID(parameters);  
  8.             }  
  9.             catch { }  
  10.             return View(result);  
  11.         } 
Step 5

Create a hub called "CustomerHub.cs". A SignalR Hub makes the remote procedure calls (RPCs) from a Server to connected clients and from clients to the Server.

Description

It gets the CustomerHub context. 
  1. IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CustomerHub>(); 
It calls the client part of SignalR and tells it to execute the JavaScript method updatedData().
  1. context.Clients.All.updatedData(); 
Step 6

Create an Entity Framework model named "Customer_Model.edmx" under Models folder.

Description


Here, you can add your Customer table. 
 
Step 7

Create a class file called "GenericRepository.cs" in the Repository folder.

Description


The code is described with green line comment mark.

Then, create another class file called "iRepository.cs" in the Repository folder.

Description

interfaceIRepository<T> Shows an interface of a generic repository of type T, which is a LINQ to SQL entity. It provides a basic interface with operations like Insert, Update, Delete, GetById, and GetAll.

IDisposable - The IDisposable Interface provides a mechanism for releasing unmanaged resources.

whereT : class is constraining the generic parameter to a class.

The type of argument must be a reference type; this applies also to any class, interface, delegate, or array type. 
 
Step 8

Create a class file called "CustomerService". It acts as a BAL and DAL file here. I have added all 5 stored procedures mentioned under related method name.

For example
 
Insert Method
  1. public int Insert(object[] parameters)  
  2.         {  
  3.             string spQuery = "[Set_Customer] {0}, {1}";  
  4.             return CustRepository.ExecuteCommand(spQuery, parameters);  
  5.         } 
Step9

Then, add 4 Views as mentioned in the image below.
 


Description


The codes will be available in my Github link.
  • In "_DataList.cshtml" i designed for table structure with heading and update and delete link button.
  • In "Index.cshtml" it is designed for fetch all records.
  • In "Insert.cshtml" it is designed for to insert records.
  • In "Update.cshtml" it is designed for to update records.

Step 10

Configure SignalR


The first thing is getting a reference from NuGet. Install-Package Microsoft.AspNet.SignalR using NuGet. Once you have installed it, let’s create OwinStartup Class called "Startup.cs".

The following code adds a simple piece of middleware to the OWIN pipeline, implemented as a function that receives a Microsoft.Owin.IOwinContext instance.

When the Server receives an HTTP request, the OWIN pipeline invokes the middleware. The middleware sets the content type
for the response and writes the response body.

OUTPUT

Index page



Insert Page



Update Page




Delete Function




Mobile View Insert Page



Gif Image For Better Understanding


It works without reloading the page in the same and different browser of same instance or different instance.



 
Summary

That's it. I hope you will find this article helpful while learning about the signalR, MVC, and related technologies.