【发布时间】:2015-06-15 06:31:56
【问题描述】:
我正在使用 ASP.NET MVC 4 应用程序,我需要通过从控制器向客户端发送消息来在客户端中显示消息。
我需要将文件上传到服务器并在 Foreach 循环中进行一些处理,并且每次 foreach 我需要在 UI 中显示消息。 目前我有for循环,在这种情况下,我需要在每个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();
}
【问题讨论】:
-
初始化
List<string>并向其发送消息,然后将其分配给ViewBag(或者最好是视图模型)属性,以便您可以在视图中进行迭代。 -
如果您正在查看客户端浏览器的
on the fly进度消息,那么您必须使用SignalR之类的东西。使用传统的 ASP.Net MVC api,您无法将通知推送到客户端浏览器。 -
我是 MVC 4 的新手,你能帮我怎么做吗,比如 HTTP 响应消息
-
我建议使用ajax循环并在服务器中执行与该循环相对应的操作,同时您可以将消息显示给客户
-
Vivekh 你能告诉我怎么做吗
标签: c# asp.net asp.net-mvc asp.net-mvc-4