View
@{
ViewBag.Title = "Progress bar test";
}
@section scripts {
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var proxy = $.connection.aMockThreadHub; // !!!!must start with lower case !!
// Create a function that the hub can call back to display messages.
proxy.client.updateProgress = function (status) {
status |= 0;
// Add the message to the page.
$('#progress-bar').css("width", status + "%");
$("#progress-text").html(status + "%");
};
$.connection.hub.start().done(function () {
});
});
// This optional function html-encodes messages for display in the page.
</script>
}
<div class="progress" style="margin-top: 200px">
<div class="progress-bar" id="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:0">
<span id="progress-text"></span>
</div>
</div>
需要注意hub class名在js中是小写开头的,不然找不到
SignalR class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRStudyFromNoam.SignalR
{
public class AMockThreadHub : Hub
{
public void DoSomeBackendJob()
{
Task.Run(() =>
{
double state = 1;
while (state < 100)
{
state += new Random().Next(5) ;
if (state > 100) state = 100;
Thread.Sleep(700);
var context = GlobalHost.ConnectionManager.GetHubContext<AMockThreadHub>();
context.Clients.All.updateProgress(state);
}
});
}
}
}
Startup.cs
app.MapSignalR();
Controller
public ActionResult Index()
{
new AMockThreadHub().DoSomeBackendJob();
return View();
}