Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display all images in a folder in MVC. With a foreach

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" />

}
like image 539
Chris reed Avatar asked Apr 13 '13 15:04

Chris reed


People also ask

How to display image from folder in ASP net MVC?

There is a very simple way to store images in database from MVC application. Step 1: First we create a class in model folder. Step 2: Create Action Method in Controller class . Step 6: Display an image form database on view.

What is foreach loop in MVC?

Generally, the loops in asp.net mvc razor view will work same as other programming languages. We can define the loop inside or outside the code block in razor, and we can use the same foreach looping concept to assign value to define the condition.

How many views does the model can have in MVC?

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible.


1 Answers

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" />
}
like image 123
p.s.w.g Avatar answered Oct 01 '22 03:10

p.s.w.g