【发布时间】:2017-11-24 22:03:59
【问题描述】:
浏览了 Google 的前 3 页,但仍然无法深入了解。我有一个控制器用来上传图片:
[HttpPost]
[Authorize(Roles = "Admin,Tradesman,Customer")]
public ActionResult UploadFile(HttpPostedFileBase file)
{
// to do: ensure only valid file types are sent
try
{
if (file.ContentLength > 0)
{
using (var ctx = new ApplicationDbContext())
{
if (ModelState.IsValid)
{
// Need to check we have a current UserId and JobId before we go any furthur
var profileData = Session["UserProfile"] as UserProfileSessionData;
if (profileData.JobIdGuid.ToString().Length != 36)
{
// to do: something went horribly wrong! Redirect back to main view
}
if (profileData.UserIdGuid.ToString().Length != 36)
{
// to do: something went horribly wrong! Redirect back to main view
}
var photo = new Photos();
photo.Guid = Guid.NewGuid();
photo.Url = Server.MapPath("~/Images/2017");
photo.Extension = Path.GetExtension(file.FileName);
photo.JobGuid = profileData.JobIdGuid;
photo.UserIdGuid = profileData.UserIdGuid;
photo.Timestamp = DateTime.Now;
ctx.Photo.Add(photo);
ctx.SaveChanges();
string _path = Path.Combine(photo.Url, photo.Guid.ToString() + photo.Extension);
file.SaveAs(_path);
}
}
}
ViewBag.Message = "File Uploaded Successfully.";
return View();
}
catch
{
ViewBag.Message = "File upload failed.";
return View();
}
}
每张图片都保存到给定的位置,保存到db的位置,快乐的日子。我想要的是让我的图像在每次上传后显示在同一页面上。该模型与您期望的一样,只是 Id、Guid、Url、Extension、UserId、Timestamp。
这是上传图片的视图:
@{
ViewBag.Title = "UploadFile";
}
<h2>Upload File</h2>
@using (Html.BeginForm("UploadFile", "Job", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.TextBox("file", "", new { type = "file" })
<br />
<input type="submit" value="Next" />
@ViewBag.Message
</div>
// to do display the images uploaded
}
是否可以只使用某种 for...each 并将每个都显示在底部?有人知道怎么做吗!顺便说一句,这是我的第一个 C# MVC 应用程序,所以如果这是一个愚蠢的问题,我深表歉意。在此先感谢:)
【问题讨论】:
-
您应该重定向到 GET 操作,您将在其中读取数据并显示在您的视图中。遵循 PRG 模式。
标签: c# asp.net-mvc entity-framework image-processing asp.net-mvc-5