MVC4从服务器回调客户端

我正在使用ASP.NET MVC 4应用程序,我需要通过从Controller向客户端发送消息来在客户端中显示消息。

我需要将文件上传到Server并在Foreach循环中执行一些处理,并且每次foreach我都需要在UI中显示消息。 目前我对循环我需要在这种情况下在每个for循环上从服务器发送消息到客户端

视图

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" })) { 
Upload File
@ViewBag.Message

}

控制器代码

 [HttpPost] public ActionResult Index(HttpPostedFileBase file) { if (file != null) { var fname = Path.GetFileName(file.FileName); var exis = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Storage/uploads"), fname); if (System.IO.File.Exists(exis)) { ViewData["Message"] = "The file " + fname + " has already exists"; } else { try { if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var folderPath = Server.MapPath("~/Storage/uploads"); fname = fileName; var path = Path.Combine(folderPath, fileName); var filebytes = new byte[file.ContentLength]; if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); file.SaveAs(path); for (int i = 0; i < 20; i++) { //Display This Message in UI From here each time for runs like i want to show user message 1,2,3,4 etc each time for runs } } ViewData["Message"] = "The file " + fname + " has uploaded successully"; } catch (Exception e) { ViewData["Message"] = "The file " + fname + " Could not upload"; ViewData["Message"] = e.Message; } } } else ViewData["Message"] = "Please choose file"; return View(); } 

您可以在循环的每次迭代中创建字典键值对

 for (int i = 0; i < 20; i++) { ViewData["Message_"+i.ToString()] = //your message; } 
 You can use `StringBuilder`: var sb = new StringBuilder(); for (int i = 0; i < 20; i++) { bool isValid = doSomeThing(); if (isValid) { sb.Append("
  • Loop success : " + i + "
  • "); } else { sb.Append("
  • Error in loop : " + i + "
  • "); } } viewBag.msg = sb.toString();