asp.net - 遍历目录并使用 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();
}

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

“~/Content/img/Media/Photos/GALLERYNAME”

我不确定我是否应该直接在我的 View 中或在我的 Controller 的 Gallery ActionResult 中执行此循环,然后传递包含所有图像路径的字符串列表。当我在 Controller 中尝试使用 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的物理路径。然后将它与画廊名称结合起来。

我个人会在您的 Controller 中执行此操作,为您的 View 提供文件列表(可能转换为某种 View 模型),但您也可以在您的 View 中执行此操作:

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

https://stackoverflow.com/questions/32911619/

相关文章:

javascript - 纯函数是幂等的吗?

php - 如何使用 FDI/FPDF 从 PDF 中删除文本

codeigniter - 如何从 codeigniter 中的另一个 Controller 调用

Emacs - 多行搜索

google-sheets - 将字符串转换为可以传递给函数的单元格引用

php - Goutte 客户端将 cookie 保存到文件

layout - matplotlib:获取子图布局?

math - XOR 在数学上有什么作用?

drupal - 如何在更新模块之前检查是否需要更新数据库

arrays - 如何证明从完全二叉树到数组的转换?