在本文中,您將學(xué)到在現(xiàn)有 ASP.NET MVC 框架的 CRUD 項(xiàng)目中,如何使用 SignalR 類庫(kù),顯示來(lái)自數(shù)據(jù)庫(kù)的實(shí)時(shí)更新。在這一主題中,我們將重點(diǎn)放在在現(xiàn)有 ASP.NET MVC 框架的 CRUD 項(xiàng)目中,如何使用 SignalR 類庫(kù),顯示來(lái)自數(shù)據(jù)庫(kù)的實(shí)時(shí)更新。 本文系國(guó)內(nèi) ITOM 管理平臺(tái) OneAPM 工程師編譯整理。
創(chuàng)新互聯(lián)建站是一家專注于成都做網(wǎng)站、網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)與策劃設(shè)計(jì),西充網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:西充等地區(qū)。西充做網(wǎng)站價(jià)格咨詢:13518219792
本主題有以下兩個(gè)步驟:
我們將創(chuàng)建一個(gè)示例應(yīng)用程序來(lái)執(zhí)行 CRUD 操作。
我們將使用 SignalR 類庫(kù)讓?xiě)?yīng)用實(shí)時(shí)。
那些不熟悉 SignalR 的,請(qǐng)?jiān)L問(wèn)我以前有關(guān) SignalR 概述 的文章。
我們需要?jiǎng)?chuàng)建一個(gè)名為 CRUD_Sample 的數(shù)據(jù)庫(kù)。在示例數(shù)據(jù)庫(kù)中創(chuàng)建一個(gè)名為 Customer 的表。
CREATE TABLE [dbo].[Customer]( [Id] [bigint] IDENTITY(1,1)NOTNULL, [CustName] [varchar](100)NULL, [CustEmail] [varchar](150)NULL )
存儲(chǔ)過(guò)程
USE [CRUD_Sample] GO /****** Object: StoredProcedure [dbo].[Delete_Customer] Script Date: 12/27/2015 1:44:05 PM ******/ SETANSI_NULLSON GO SETQUOTED_IDENTIFIERON GO -- ============================================= -- Author:-- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[Delete_Customer] -- Add the parameters for the stored procedure here @Id Bigint AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SETNOCOUNTON; -- Insert statements for procedure here DELETE FROM [dbo].[Customers] WHERE [Id] = @Id RETURN 1 END GO /****** Object: StoredProcedure [dbo].[Get_Customer] Script Date: 12/27/2015 1:44:05 PM ******/ SETANSI_NULLSON GO SETQUOTED_IDENTIFIERON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[Get_Customer] -- Add the parameters for the stored procedure here @Count INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SETNOCOUNTON; -- Insert statements for procedure here SELECT top(@Count)*FROM [dbo].[Customers] END GO /****** Object: StoredProcedure [dbo].[Get_CustomerbyID] Script Date: 12/27/2015 1:44:05 PM ******/ SETANSI_NULLSON GO SETQUOTED_IDENTIFIERON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[Get_CustomerbyID] -- Add the parameters for the stored procedure here @Id BIGINT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SETNOCOUNTON; -- Insert statements for procedure here SELECT*FROM [dbo].[Customers] WHERE Id=@Id END GO /****** Object: StoredProcedure [dbo].[Set_Customer] Script Date: 12/27/2015 1:44:05 PM ******/ SETANSI_NULLSON GO SETQUOTED_IDENTIFIERON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[Set_Customer] -- Add the parameters for the stored procedure here @CustNameNvarchar(100) ,@CustEmailNvarchar(150) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SETNOCOUNTON; -- Insert statements for procedure here INSERT INTO [dbo].[Customers]([CustName],[CustEmail]) VALUES(@CustName,@CustEmail) RETURN 1 END GO /****** Object: StoredProcedure [dbo].[Update_Customer] Script Date: 12/27/2015 1:44:05 PM ******/ SETANSI_NULLSON GO SETQUOTED_IDENTIFIERON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[Update_Customer] -- Add the parameters for the stored procedure here @Id Bigint ,@CustNameNvarchar(100) ,@CustEmailNvarchar(150) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SETNOCOUNTON; -- Insert statements for procedure here UPDATE [dbo].[Customers] SET[CustName] = @CustName,[CustEmail]= @CustEmail WHERE [Id] = @Id RETURN 1 END GO
創(chuàng)建示例應(yīng)用程序,我們需要 Visual Studio 2012 或更高版本,并且該服務(wù)器平臺(tái)必須支持 .NET 4.5。
步驟 1:
Step 2:
Step 3:
點(diǎn)擊 OK,Visual Studio 將會(huì)創(chuàng)建一個(gè)新的 ASP.NET 工程。
使用通用功能,我們可以減少代碼數(shù)量。
namespace WebApplication1.Repository { interfaceIRepository < T > : IDisposablewhereT: class { IEnumerable < T > ExecuteQuery(stringspQuery, object[] parameters); TExecuteQuerySingle(stringspQuery, object[] parameters); intExecuteCommand(stringspQuery, object[] parameters); } }
顯示一個(gè)通用類庫(kù)的 T 型接口,它是 SQL 實(shí)體的 LINQ。它提供了一個(gè)基本的界面操作,如 Insert, Update, Delete, GetById and GetAll。
IDisposable接口提供了一種機(jī)制,釋放非托管資源。
這是制約泛型參數(shù)的一類。點(diǎn)擊查看更多。
類型參數(shù)必須是引用類型;這也適用于任何類,接口,委托或數(shù)組類型。
namespace WebApplication1.Repository { public class GenericRepository < T > : IRepository < T > whereT: class { Customer_Entities context = null; privateDbSet < T > entities = null; public GenericRepository(Customer_Entities context) { this.context = context; entities = context.Set < T > (); } ////// Get Data From Database /// public IEnumerable < T > ExecuteQuery(stringspQuery, object[] parameters) { using(context = newCustomer_Entities()) { returncontext.Database.SqlQuery < T > (spQuery, parameters).ToList(); } } ///Use it when to retive data through a stored procedure ////// Get Single Data From Database /// public TExecuteQuerySingle(stringspQuery, object[] parameters) { using(context = newCustomer_Entities()) { returncontext.Database.SqlQuery < T > (spQuery, parameters).FirstOrDefault(); } } ///Use it when to retive single data through a stored procedure ////// Insert/Update/Delete Data To Database /// public intExecuteCommand(stringspQuery, object[] parameters) { int result = 0; try { using(context = newCustomer_Entities()) { result = context.Database.SqlQuery < int > (spQuery, parameters).FirstOrDefault(); } } catch {} return result; } private bool disposed = false; protected virtualvoid Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }Use it when to Insert/Update/Delete data through a stored procedure ///
namespace WebApplication1.Services { public partial class CustomerService { privateGenericRepository < Customer > CustRepository; //CustomerRepositoryCustRepository; public CustomerService() { this.CustRepository = newGenericRepository < Customer > (newCustomer_Entities()); } public IEnumerable < Customer > GetAll(object[] parameters) { stringspQuery = "[Get_Customer] {0}"; returnCustRepository.ExecuteQuery(spQuery, parameters); } public CustomerGetbyID(object[] parameters) { stringspQuery = "[Get_CustomerbyID] {0}"; returnCustRepository.ExecuteQuerySingle(spQuery, parameters); } public int Insert(object[] parameters) { stringspQuery = "[Set_Customer] {0}, {1}"; returnCustRepository.ExecuteCommand(spQuery, parameters); } public int Update(object[] parameters) { stringspQuery = "[Update_Customer] {0}, {1}, {2}"; returnCustRepository.ExecuteCommand(spQuery, parameters); } public int Delete(object[] parameters) { stringspQuery = "[Delete_Customer] {0}"; returnCustRepository.ExecuteCommand(spQuery, parameters); } } }
namespace WebApplication1.Controllers { public class HomeController: Controller { private CustomerServiceobjCust; //CustomerRepositoryCustRepository; public HomeController() { this.objCust = newCustomerService(); } // GET: Home public ActionResult Index() { int Count = 10; object[] parameters = { Count }; var test = objCust.GetAll(parameters); return View(test); } public ActionResult Insert() { return View(); } [HttpPost] public ActionResult Insert(Customer model) { if (ModelState.IsValid) { object[] parameters = { model.CustName, model.CustEmail }; objCust.Insert(parameters); } return RedirectToAction("Index"); } public ActionResult Delete(int id) { object[] parameters = { id }; this.objCust.Delete(parameters); return RedirectToAction("Index"); } public ActionResult Update(int id) { object[] parameters = { id }; return View(this.objCust.GetbyID(parameters)); } [HttpPost] public ActionResult Update(Customer model) { object[] parameters = { model.Id, model.CustName, model.CustEmail }; objCust.Update(parameters); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
@model IList@{ ViewBag.Title = "Index"; }
@model WebApplication1.Models.Customer @{ ViewBag.Title = "Insert"; }@using (Html.BeginForm("Insert", "Home", FormMethod.Post)) { @*
*@ ID @Html.TextBoxFor(m =>m.Id) Name @Html.TextBoxFor(m =>m.CustName) Email ID @Html.TextBoxFor(m =>m.CustEmail) } @Html.ActionLink("Home", "Index", "Home")
@model WebApplication1.Models.Customer @{ ViewBag.Title = "Update"; }
Name Email ID Update @using (Html.BeginForm("Update", "Home", FormMethod.Post)) { @Html.TextBoxFor(m =>m.CustName) @Html.TextBoxFor(m =>m.CustEmail) }
第一件事是獲得 NuGet 參照。
在 NuGet 上獲得。
安裝 Microsoft.AspNet.SignalR 包
Microsoft.AspNet.SignalR
安裝后需要?jiǎng)?chuàng)建 OwinStartup 類。
下面的代碼將一段簡(jiǎn)單中間件向 OWIN 管道,實(shí)現(xiàn)接收 Microsoft.Owin.IOwinContext 實(shí)例的功能。
當(dāng)服務(wù)器收到一個(gè) HTTP 請(qǐng)求,OWIN 管道調(diào)用中間件。中間件設(shè)置內(nèi)容類型的響應(yīng)和寫(xiě)響應(yīng)體。
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof (WebAppSignalR.Startup))] namespace WebAppSignalR { public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } }
完成前面的過(guò)程之后,創(chuàng)建一個(gè) Hub。一個(gè)SignalR Hub 讓從服務(wù)器到客戶端連接,并從客戶端到服務(wù)器的遠(yuǎn)程過(guò)程調(diào)用(RPC)。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; namespace WebApplication1.Hubs { public class CustomerHub: Hub { [HubMethodName("broadcastData")] public static void BroadcastData() { IHubContext context = GlobalHost.ConnectionManager.GetHubContext < CustomerHub > (); context.Clients.All.updatedData(); } } }
IHubContext context = GlobalHost.ConnectionManager.GetHubContext();
context.Clients.All.updatedData();
它請(qǐng)求 SignalR 的客戶端部分,并告訴它執(zhí)行 JavaScript 的 updatedData()方法。
修改一部分索引視圖,將通過(guò)局部視圖顯示數(shù)據(jù)。
@model IList < WebApplication1.Models.Customer > @ { ViewBag.Title = "Index"; } < linkhref = "~/Content/bootstrap/css/bootstrap.min.css" rel = "stylesheet" / > < divclass = "clearfix" > & nbsp; < /div> < divclass = "clearfix" > & nbsp; < /div> < divclass = "container" > < divclass = "table-responsive" > @Html.ActionLink("New Customer", "Insert", "Home") < hr / > < divid = "dataTable" > < /div> < /div> < divclass = "clearfix" > & nbsp; < /div> < /div> @section JavaScript { < scriptsrc = "~/Scripts/jquery.signalR-2.2.0.min.js" > < /script> < scriptsrc = "/signalr/hubs" > < /script> < scripttype = "text/javascript" > $(function () { // Reference the hub. var hubNotif = $.connection.customerHub; // Start the connection. $.connection.hub.start().done(function () { getAll(); }); // Notify while anyChanges. hubNotif.client.updatedData = function () { getAll(); }; }); function getAll() { var model = $('#dataTable'); $.ajax( { url: '/home/GetAllData', contentType: 'application/html ; charset:utf-8', type: 'GET', dataType: 'html' }).success(function (result) { model.empty().append(result); }).error(function (e) { alert(e); }); } < /script> }
ID | Name | Email ID | Delete | Update |
---|---|---|---|---|
@item.Id | @item.CustName | @item.CustEmail | @Html.ActionLink("Delete", "Delete", "Home", new { id = @item.Id }, null) | @Html.ActionLink("Update", "Update", "Home", new { id = @item.Id }, null) |
在主 Controller,我們將添加一個(gè)名為 GetAllDaTa()的方法。這是方法。
[HttpGet] public ActionResult GetAllData() { int Count = 10; object[] parameters = { Count }; var test = objCust.GetAll(parameters); return PartialView("_DataList", test); }
在這里,返回局部視圖返回的數(shù)據(jù)列表,且只返回空。
// GET: Home public ActionResult Index() { return View(); }
public class HomeController: Controller { private CustomerService objCust; //CustomerRepositoryCustRepository; public HomeController() { this.objCust = newCustomerService(); } // GET: Home public ActionResult Index() { return View(); } [HttpGet] public ActionResult GetAllData() { int Count = 10; object[] parameters = { Count }; var test = objCust.GetAll(parameters); return PartialView("_DataList", test); } public ActionResult Insert() { return View(); } [HttpPost] public ActionResult Insert(Customer model) { if (ModelState.IsValid) { object[] parameters = { model.CustName, model.CustEmail }; objCust.Insert(parameters); } //Notify to all CustomerHub.BroadcastData(); return RedirectToAction("Index"); } public ActionResult Delete(int id) { object[] parameters = { id }; this.objCust.Delete(parameters); //Notify to all CustomerHub.BroadcastData(); return RedirectToAction("Index"); } public ActionResult Update(int id) { object[] parameters = { id }; return View(this.objCust.GetbyID(parameters)); } [HttpPost] public ActionResult Update(Customer model) { object[] parameters = { model.Id, model.CustName, model.CustEmail }; objCust.Update(parameters); //Notify to all CustomerHub.BroadcastData(); returnRedirectToAction("Index"); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } }
希望能夠幫助到您。
OneAPM 助您輕松鎖定 .NET 應(yīng)用性能瓶頸,通過(guò)強(qiáng)大的 Trace 記錄逐層分析,直至鎖定行級(jí)問(wèn)題代碼。以用戶角度展示系統(tǒng)響應(yīng)速度,以地域和瀏覽器維度統(tǒng)計(jì)用戶使用情況。想閱讀更多技術(shù)文章,請(qǐng)?jiān)L問(wèn) OneAPM 官方博客。
本文轉(zhuǎn)自 OneAPM 官方博客
原文地址: http://www.c-sharpcorner.com/UploadFile/302f8f/Asp-Net-mvc-real-time-app-with-signalr/