Jay*_*thy 20 asp.net ajax asp.net-mvc
我只想在长时间运行服务器调用时创建进度条.当控制器执行长时间运行的作业时,我无法向控制器创建ajax post请求.
我想创建一个额外的操作来获取当前长时间运行任务的实际声明.我尝试在ajax请求中创建轮询,然后我可以从服务器端返回状态并将其显示在客户端进度条中.有任何想法吗 ?
Jay*_*thy 43
最简单的方法是使用SignalR.请在https://www.nuget.org/packages/Microsoft.AspNet.SignalR/2.1.2下载Microsoft SignalR
在名为hubs的项目路径中的单独文件夹中创建hub类,将两个类文件添加到hubs文件夹中
Startup.cs
using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}
Run Code Online (Sandbox Code Playgroud)
ProgressHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace RealTimeProgressBar
{
public class ProgressHub : Hub
{
public string msg = "Initializing and Preparing...";
public int count = 1;
public static void SendMessage(string msg , int count)
{
var message = "Process completed for " + msg;
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
hubContext.Clients.All.sendMessage(string.Format(message), count);
}
public void GetCountAndMessage()
{
Clients.Caller.sendMessage(string.Format(msg), count);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,
// assemblies
using Microsoft.AspNet.SignalR;
using RealTimeProgressBar;
//call this method inside your working action
ProgressHub.SendMessage("initializing and preparing", 2);
Run Code Online (Sandbox Code Playgroud)
在视图中,
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script type="text/javascript">
$(document).ready(function () {
$("#progressBar").kendoProgressBar({
min: 0,
max: 100,
type: "percent",
});
});
function StartInvoicing()
{
var progressNotifier = $.connection.progressHub;
// client-side sendMessage function that will be called from the server-side
progressNotifier.client.sendMessage = function (message, count) {
// update progress
UpdateProgress(message, count);
//alert(message);
};
// establish the connection to the server and start server-side operation
$.connection.hub.start().done(function () {
// call the method CallLongOperation defined in the Hub
progressNotifier.server.getCountAndMessage();
});
}
// Update the progress bar
function UpdateProgress(message, count) {
var result = $("#result");
result.html(message);
$("#progressBar").data("kendoProgressBar").value(count);
}
</script>
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅谷歌的一些现有文章
| 归档时间: |
|
| 查看次数: |
50160 次 |
| 最近记录: |