我想将文件夹“Images_uploads”文件夹中的所有图片显示到 MVC View 中。所以它显示在网站上。但似乎没有任何效果..
{
<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" />
}
最佳答案
您可能应该在您的 Controller 中执行此类操作。使用 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" />
}
更好的是,使用强类型 View 模型,如下所示:
// 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" />
}
关于c# - 在 MVC 中显示文件夹中的所有图像。用一个foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15989764/