我想在我的文件夹“Images_uploads”文件夹中将我的所有图片显示到MVC视图中。所以它在网站上显示。但似乎没有任何作用..
{
<form method="post" action="/Images_upload" enctype="multipart/form-data">
<input name="ImageUploaded" type="file">
<input type="submit">
</form>
<List<String> li = ViewData["~/images_upload"] as List<String>;
foreach (var picture in li)
<img src = '@Url.Content("~/images_upload" + picture)' alt="Hejsan" />
}
答案 0 :(得分:21)
您应该在控制器中执行此类操作。使用EnumerateFiles
获取文件夹中所有文件的列表:
// controller
public ActionResult MyAction()
{
...
ViewBag.Images = Directory.EnumerateFiles(Server.MapPath("~/images_upload"))
.Select(fn => "~/images_upload/" + Path.GetFileName(fn));
return View(...);
}
// view
@foreach(var image in (IEnumerable<string>)ViewBag.Images))
{
<img src="@Url.Content(image)" alt="Hejsan" />
}
更好的是,使用强类型视图模型,如下所示:
// model
class MyViewModel
{
public IEnumerable<string> Images { get; set; }
}
// controller
public ActionResult MyAction()
{
var model = new MyViewModel()
{
Images = Directory.EnumerateFiles(Server.MapPath("~/images_upload"))
.Select(fn => "~/images_upload/" + Path.GetFileName(fn))
};
return View(model);
}
// view
@foreach(var image in Model.Images)
{
<img src="@Url.Content(image)" alt="Hejsan" />
}