前端代碼 對應頁面引入signalR.js 初始化signalR 連接 定義後端推送action 渲染進度條 本次用的是jeasyui 進度條彈窗 實際效果圖 參考地址 https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/ ...
- 需求背景 產品覺得在後臺處理數據時給前端加個進度條
- 項目框架 .ENT framework4.5 MVC 5.0
- Nuget引入 Microsoft.Owin 系列 2.0.2
- Nuget引入 Microsoft.AspNet.SignalR 系列 2.0.3
- 伺服器代碼 選擇已安裝 > Visual C# > Web > SignalR ,然後選擇SignalR Hub 類 (v2)
-
using System; using System.Collections.Generic; using System.Linq; using System.Web; using XXX.WMS.Core.Log; using Microsoft.AspNet.SignalR; namespace XXX.WebUI { public class SaleBackHub : Hub { private void Send(string connectionId, string percent) { // Call the addNewMessageToPage method to update clients. try { Clients.Client(connectionId).updateProgressbar(percent); } catch (Exception ex) { LoggerManager.GetInstance().Fatal(ex); } } public string GetConnectionId() { return this.Context.ConnectionId; } } }
- 服務端調用前端action更新進度條
1 //使用外部方式調用Hub類方法 2 var saleBackHub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<SaleBackHub>(); 3 var percent = 0; 4 if (!string.IsNullOrWhiteSpace(requestDto.ProgressbarKey)) 5 { 6 percent = (int)((decimal)++progressCount / (decimal)saleBackModelListCount * 100); 7 try 8 { 9 //調用前端action 更新進度條 10 saleBackHub.Clients.Client(requestDto.ProgressbarKey).updateProgressbar(percent.ToString()); 11 } 12 catch (Exception ex) 13 { 14 throw; 15 } 16 }
-
- 服務添加Starup.cs
-
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(Frxs.WMS.Management.WebUI.Startup))] namespace xxx.WMS.Management.WebUI { public class Startup { public void Configuration(IAppBuilder app) { // 有關如何配置應用程式的詳細信息,請訪問 https://go.microsoft.com/fwlink/?LinkID=316888 app.MapSignalR(); } } }
-
-
前端代碼
-
對應頁面引入signalR.js
<script src="@Url.Content("~/Scripts/signalR/jquery.signalR-2.0.3.min.js“)" type="text/javascript"></script> <script src="~/signalr/hubs"></script>
-
初始化signalR 連接 定義後端推送action 渲染進度條 本次用的是jeasyui 進度條彈窗
var chat; var chatConnectionId; function initchatHub() { // Reference the auto-generated proxy for the hub. chat = $.connection.saleBackHub; $.connection.hub.logging = true; // Get the user name and store it to prepend to messages. // Set initial focus to message input box. // Start the connection. $.connection.hub.start().done(function () { chat.server.getConnectionId().done(function (connectionId) { chatConnectionId = connectionId; }); }); // Create a function that the hub can call back to display messages. chat.client.updateProgressbar = function (percent) { // Add the message to the page. if (parseInt(percent) <= 100) { $.messager.progress('bar').progressbar('setValue', percent); } //var value = $.messager.progress('bar').progressbar('getValue'); }; } function showProgressbar() { $.messager.progress({ title: '測試進度條', interval: 0 //每次進度更新之間以毫秒為單位的時間長度。預設值是 300。 }); }
-
-
實際效果圖
-
參考地址 https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/