从服务器回叫到客户端 [英] Call back from server to client
问题描述
我正在使用ASP.NET MVC 4应用程序,我需要通过从Controller向客户端发送消息来在客户端中显示消息.
I am using ASP.NET MVC 4 application, I need to Display messages in the Client, by sending messages from Controller to Client.
我的要求是用户单击UI中的按钮,然后我将处理服务器上的文件,并在我处理的每个foreach文件的末尾在UI中显示消息.我需要在使用ASP.NET MVC的客户端中显示文件名.
My requirement is user click a button in UI and i will process the files on the server and Display message in UI on end of each foreach file i process. i need to show the File names in the Client Using ASP.NET MVC.
任何人都可以通过每次在for-each循环上从服务器调用客户端方法来帮助如何在客户端中显示消息.
Can any one Help how to show the messages in the Client by calling client method from server on for-each loop each time.
我能够调用控制器并将每个控制器的末尾发送最终消息到UI,但是如何在每个foreach循环迭代中发送?
I am able to call the controller and end of each controller I am sending final message to UI, but how to send on each foreach loop iteration?
推荐答案
您必须编写一个ActionResult
,以便逐步将结果写入响应中.因此您可以在每个foreach循环迭代中向用户显示一些数据.我写了一个简单的ActionResult
,每2秒写一个数字:
You have to write an ActionResult
that progressively write result to the response. so you can show the user some data in every foreach loop iteration. I have written a simple ActionResult
that writes a number every 2 seconds:
public class ProgressiveResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
for (int i = 0; i < 20; i++)
{
context.HttpContext.Response.Write(i.ToString());
Thread.Sleep(2000);
context.HttpContext.Response.Flush();
}
context.HttpContext.Response.End();
}
}
这是一个返回此结果的动作:
and this is an action that returns this result:
public ActionResult LongProcess()
{
return new ProgressiveResult();
}
因此您可以编写ActionResult
并使用ExecuteResult
方法编写foreach
代码.
So you can write an ActionResult
and write your foreach
code in ExecuteResult
method.
更新:
您可以使用Ajax请求进行此调用,并使用简单的代码(如以下代码)返回结果:
You can make this call with an Ajax request and return result with a simple code like the following code:
var result = "";
function showResult() {
if (result !== oReq.responseText) {
result = oReq.responseText;
console.log(result);
}
}
var oReq = new XMLHttpRequest();
oReq.open("get", "/Home/LongProcess", true);
oReq.send();
setInterval(showResult, 1000);
这篇关于从服务器回叫到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!