Displaying multiple images from database in view

567 views c#
0

I am working on a project where users should be able to upload images and have them shown on their individual page as a grid gallery.

I have watched this tutorial to be able to upload images from the application to the database and show an image with a specific ID. It all works fine.

https://www.youtube.com/watch?v=5L5W-AE-sEs&

My view controller looks like this:

[HttpGet]
        public ActionResult View(int id)
        {
            Image imageModel = new Image();
            using (portfolio_project_dbEntities db = new portfolio_project_dbEntities())
            {
                imageModel = db.Images.Where(x => x.ImageID == id).FirstOrDefault();
            }
            return View(imageModel);
        }

The view part:

<img src="@Url.Content(Model.ImagePath)" width="200"/>

Now I would like to be able to show multiple images on one page (images with the same userid) but I don't really understand how to do this. How do I pass multiple images from the controller to the view? Or maybe this is better to do in the view?

answered question

You may also want to consider creating a View Model for this that has a public List<Image> Images {get; set; } on it.

1 Answer

13

The FirstOrDefault method returns a single item(or default) from a collection. So in the code you shared in the question where you are filtering the images using this expression .Where(x => x.ImageID == id) and then calling the FirstOrDefault method on that, which will yield a single item at max.

So If you want to show more than one item, remove that FirstOrDefault method call. In the below sample, I am assuming your Image object has a UserId property of int type and you want to filter the Image objects with UserId value same as your parameter value. So use an expression to check that in your Where method.

[HttpGet]
public ActionResult View(int id)
{
   var images = new List<Image>();
   var db = new portfolio_project_dbEntities())
   {
      images  = db.Images
                  .Where(x => x.UserId == id)
                  .ToList();
    }
    // images is a list of Image objects. Let's pass it to the view.
    return View(images);
 }

Now since you are passing a collection of Image objects to the view, make sure your view is strongly typed to a collection of Image.

@model IEnumerable<YourNamespaceHere.Image>
<h1>Images</h1>
@foeach(var img in Model)
{
  <img src="@Url.Content(img .ImagePath)" width="200"/>
}

posted this

Have an answer?

JD

Please login first before posting an answer.