MVC4从服务器回调客户端

时间:2015-06-15 06:31:57

标签: c# asp.net asp.net-mvc asp.net-mvc-4

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

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

查看

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
    <div>
        <b>Upload File</b>
        <input type="file" name="file" />
        <input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus();"/><br />
    </div>
    <div>
        @ViewBag.Message
    </div>
    <div style="width: 30%; margin: 0 auto;">
        <div id="progressbar" style="width: 300px; height: 15px"></div>
        <br />
    </div>
}

控制器代码

[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();
}

2 个答案:

答案 0 :(得分:0)

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

for (int i = 0; i < 20; i++)
                {
                    ViewData["Message_"+i.ToString()] = //your message;
                }

答案 1 :(得分:0)

You can use `StringBuilder`:

    var sb = new StringBuilder();      

    for (int i = 0; i < 20; i++)
    {
         bool isValid = doSomeThing();

         if (isValid)
         {
            sb.Append("<li>Loop success : " + i + "</li>");     
         }
         else
         {
            sb.Append("<li>Error in loop : " + i + "</li>");         
          }

      }

    viewBag.msg = sb.toString();