Display all images in a folder in MVC. Using foreach

I would like to display all my photos in the "Images_uploads" folder in MVC View. Thus, its display on the site. But nothing works.

{ <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" /> } 
+8
c # asp.net-mvc asp.net-mvc-4
source share
1 answer

You should probably do this in your controller. Use EnumerateFiles to get a list of all the 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, for example:

 // 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" /> } 
+20
source share

All Articles