8

我想将我的文件夹“Images_uploads”文件夹中的所有图片显示到 MVC 视图中。所以它在网站上显示。但似乎没有任何工作..

{

<form method="post" action="/Images_upload" enctype="multipart/form-data">  
    <input name="ImageUploaded" type="file">  
    <input type="submit">  
</form>  

<List<String> li = ViewData["~/images_upload"] as List<String>;
 foreach (var picture in li)

    <img src = '@Url.Content("~/images_upload" + picture)' alt="Hejsan" />

}
4

1 回答 1

26

你可能应该在你的控制器中做这种事情。用于EnumerateFiles获取文件夹中所有文件的列表:

// 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<string>)ViewBag.Images))
{
    <img src="@Url.Content(image)" alt="Hejsan" />
}

更好的是,使用强类型视图模型,如下所示:

// model
class MyViewModel
{
    public IEnumerable<string> 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)
{
    <img src="@Url.Content(image)" alt="Hejsan" />
}
于 2013-04-13T16:08:21.723 回答