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

后端 未结 1 842
忘掉有多难
忘掉有多难 2021-02-06 05:29

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..

{

1条回答
  •  别跟我提以往
    2021-02-06 06:24

    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)ViewBag.Images))
    {
        Hejsan
    }
    

    Even better, use a strongly-typed view model, like this:

    // model
    class MyViewModel
    {
        public IEnumerable 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)
    {
        Hejsan
    }
    

    0 讨论(0)
提交回复
热议问题