遍历目录并使用剃刀获取每个图像文件路径

Looping through a directory and getting each images filepath with razor

我正在寻找一种基于 MVC5 razor 中的 URL 循环浏览我网站文件夹中图像的好方法。

网址的结构如下:
/Home/Media/Photos/Gallery/GALLERYNAME

我将以下内容添加到我的 RouteConfig 中:

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

我的 HomeController 中有以下内容:

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

现在,基于发送到我的画廊视图的这个 ViewBag 值 'galleryName',我想遍历以下目录,这样我就可以获取每张图像并将其显示以供灯箱查看:

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

我不确定是否应该直接在我的视图中或在我的控制器的 Gallery ActionResult 中执行此循环,然后传递包含所有图像路径的字符串列表。当我在控制器中尝试使用 Directory.EnumerateFiles 时,我总是遇到问题。它正在我的 C 驱动器上搜索路径。我需要相对于我的站点的路径。有些东西告诉我,我可能需要创建一个虚拟目录来为此使用 System.IO。

如果有人想查看或评论,这是我的最终代码:

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);
}

这会生成一个可以直接进入 img src 属性的字符串列表:即 "~/Content/img/Media/Photos/myimage.jpg"

使用Server.MapPath 以获得~/Content/img/Media/Photos 的物理路径。然后将它与画廊名称结合起来。

我个人会在您的控制器中执行此操作,为您的视图提供文件列表(可能转换为某些视图模型),但您也可以在您的视图中执行此操作:

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);
}