Luk*_*e G 2 c# asp.net-mvc signalr
目前看一下使用signalR在处理时向用户呈现文件的进度报告.我正在使用asp.net MVC 4.在通过Ajax进行发布/获取时,我可以轻松获得状态更改.
因为我需要上传一个文件(没有ajax,因为1:我不能要求用户启用js才能提交文件; 2:我不相信它可以随时执行这样的任务,除了HTML5) .
编辑: 当我说我不能要求用户拥有JS时,我的意思是提交文件不能依赖JS,因为这是一个核心功能.但是,我希望那些启用了JS的人能够看到处理/导入到另一个程序的进度.我目前没有兴趣/关心实际的文件传输进度,但更多的是将状态消息发送回导入程序的当前状态.
在我调用Post表单后,为了实现更新进度的目标,将建议采用什么方法?注意:
示例代码:
$(function () {
var fileUploadHub = $.connection.fileUploadHub;
fileUploadHub.updateProgress = function (value) {
updateProgressBar(value);
};
fileUploadHub.updateStatusText = function (text) {
alert("you got to updateStatus");
updateText(text);
};
$.connection.hub.logging = true;
$.connection.hub.start();
});
function updateProgressBar(value) {
$("#progressbar").progressbar({ value: value });
}
function updateText(text) {
$("#statusText").append("<li>" + text + "</li>");
}
Run Code Online (Sandbox Code Playgroud)
//表单:由模型支持
@using (Html.BeginForm( "UploadFile", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data"}))
{
<input type="file" id="Files" name="Files" accept="text/xml" />
<br />
<input type="submit" id="submitButton" value="Submit" />
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public ActionResult SubmitFile(MyModel model)
{
...
ProcessFile(model.file)
...
}
public void ProcessFile(File file)
{
var myHub = GlobalHost.ConnectionManager.GetHubContext<FileUploadHub>();
myHub.Clients.updateStatusText("testz");
}
Run Code Online (Sandbox Code Playgroud)
轮毂类:
public class FileUploadHub : Hub
{
}
Run Code Online (Sandbox Code Playgroud)
你需要做的是用POST发回用户的SignalR ConnectionId.然后,当帖子开始时,您需要获取HubContext,并且在整个POST逻辑中,您可以通过ConnectionId将通知发送回特定客户端.
在表单中添加输入类型="隐藏".
<input type="hidden" id="mySignalRConnectionIdHidden" name="SignalRConnectionId" />
Run Code Online (Sandbox Code Playgroud)假设启用了JavaScript并连接到集线器,请在start()回调中将隐藏输入的值设置为来自SignalR的connectionid值.
$.connection.hub.start().done(function ()
{
$("#mySignalRConnectionIdHidden").val($.connection.connectionId);
});
Run Code Online (Sandbox Code Playgroud)POST到服务器端的第一步是获取Hub的HubContext并获取您将要回访的客户端.
// Get the value of the hidden from the request
string currentClientConnectionId = Request.Form["SignalRConnectionId"];
// Get the hub context
IHubContext myHubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
// Resolve a the client that corresponds to the current request
dynamic currentClient = myHubContext.Client(currentClientConnectionId);
Run Code Online (Sandbox Code Playgroud)在整个POST处理逻辑的各个点上,您现在可以将消息发送回发起上载的客户端:
... do some stuff ...
currentClient.stepOneCompleted();
.... do some more stuff ...
currentClient.stepTwoCompleted();
... etc ...
Run Code Online (Sandbox Code Playgroud)显然在步骤4中你也可以将数据作为参数传递回客户端,我只是没有在这里显示.
最后,对于没有启用JS或由于某种原因无法连接的客户端,您可以检测到POST上的表单值为空,然后您知道没有建立SignalR连接.然后你可以设置currentClient = null并在你调用客户端回调的整个地方检测到它并完全跳过回调.