William Venice
William Venice

Reputation: 329

Looping through a directory and getting each images filepath with razor

I am looking for a good way to loop through images in a folder of my website based on the URL in MVC5 razor.

The urls will be structured like this:
/Home/Media/Photos/Gallery/GALLERYNAME

I added the following to my RouteConfig:

    routes.MapRoute(
        name: "Gallery",
        url: "{controller}/Media/Photos/{action}/{galleryName}",
        defaults: new { controller = "Home", action = "Index", galleryName = UrlParameter.Optional }
    );

I have the following in my HomeController:

public ActionResult Gallery(string galleryName)
{
    ViewBag.Message = galleryName;
    return View();
}

Now based on this ViewBag value 'galleryName' that is sent to my Gallery view I would like to loop through the following directory so I can get each image and display it for lightbox viewing:

"~/Content/img/Media/Photos/GALLERYNAME"

I am not sure if I should do this looping directly in my view or in the Gallery ActionResult in my controller and then past a list of string containing all of the paths to the images. When I try it in the controller I keep having problems when using Directory.EnumerateFiles. It is searching with a path on my C drive. I need the path to be relative to my site. Something tells me I might need to create a virtual directory to use System.IO for this.

HERE IS MY FINAL CODE IF ANYONE WANTS TO SEE OR COMMENT ON:

public ActionResult Gallery(string galleryName)
{
    string galleryPath = Path.Combine(this.Server.MapPath(@"~/Content/img/Media/Photos"), galleryName);
    var fullImagePaths = Directory.GetFiles(galleryPath);

    string sitePath = "~/Content/img/Media/Photos/";
    var imagePaths = fullImagePaths.Select(fp => sitePath + Path.GetFileName(fp));

    return View(imagePaths);
}

This produces a list of strings that can go right into an img src attribute: i.e. "~/Content/img/Media/Photos/myimage.jpg"

Upvotes: 3

Views: 2305

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 34992

Use Server.MapPath in order to get the physical path of ~/Content/img/Media/Photos. Then combine it with the gallery name.

I would personally do that in your controller, providing a list of files to your view (possibly converted into some view model), but you could do it on your view as well:

public ActionResult Gallery(string galleryName)
{
    string galleryPath = Path.Combine(
             this.Server.MapPath(@"~/Content/img/Media/Photos"), 
             galleryName);

    //loop through images in the gallery folder and create list of images
    var images = ...

    return View(images);
}

Upvotes: 3

Related Questions