Reputation: 111
I would like to display all my pictures in my folder "Images_uploads" folder into MVC View. So its display on the site. But nothing seems to work..
{
<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" />
}
Upvotes: 9
Views: 20245
Reputation: 149020
You should probably do this kind of thing in your controller. Use EnumerateFiles
to get a listing of all files in a folder:
// 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" />
}
Even better, use a strongly-typed view model, like this:
// 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" />
}
Upvotes: 27