Chr*_*eed 8 c# asp.net-mvc asp.net-mvc-4
我想在我的文件夹"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" />
}
p.s*_*w.g 21
你可能应该在你的控制器中做这种事情.使用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" />
}
| 归档时间: | 
 | 
| 查看次数: | 16458 次 | 
| 最近记录: |