显示所有图像MVC中的文件夹中。在foreach [英] Display all images in a folder in MVC. With a foreach
本文介绍了显示所有图像MVC中的文件夹中。在foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想我的文件夹中,以显示我的所有照片Images_uploads文件夹到MVC视图。因此,它在网站上显示。但似乎没有任何工作。
{<形式方法=邮报行动=/ Images_uploadENCTYPE =的multipart / form-data的>
<输入名称=ImageUploaded类型=文件>
<输入类型=提交>
< /表及GT;<名单,LT;弦乐> LI =计算机[〜/ images_upload]作为名单<弦乐取代;
的foreach(李VAR图片) < IMG SRC =@ Url.Content(〜/ images_upload+图片)'ALT =Hejsan/>}
解决方案
您或许应该做这种事情在你的控制器。使用 EnumerateFiles
拿到的列表一个文件夹中的所有文件:
//控制器
公众的ActionResult MyAction()
{
...
ViewBag.Images = Directory.EnumerateFiles(使用Server.Mappath(〜/ images_upload))
。选择(FN =>中〜/ images_upload /+ Path.GetFileName(FN)); 返回查看(...);
}//视图
@foreach(在(IEnumerable的&LT VAR形象;串>)ViewBag.Images))
{
&所述; IMG SRC =@ Url.Content(图像)ALT =Hejsan/>
}
更妙的是,使用强类型的视图模式是这样的:
//模型
类MyViewModel
{
公共IEnumerable的<串GT;图片{搞定;组; }
}//控制器
公众的ActionResult MyAction()
{
VAR模型=新MyViewModel()
{
图像= Directory.EnumerateFiles(使用Server.Mappath(〜/ images_upload))
。选择(FN =>中〜/ images_upload /+ Path.GetFileName(FN))
};
返回查看(模型);
}
//视图
@foreach(在Model.Images VAR图片)
{
&所述; IMG SRC =@ Url.Content(图像)ALT =Hejsan/>
}
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..
{
<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" />
}
解决方案
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<string>)ViewBag.Images))
{
<img src="@Url.Content(image)" alt="Hejsan" />
}
Even better, use a strongly-typed view model, like this:
// 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" />
}
这篇关于显示所有图像MVC中的文件夹中。在foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文