[英]How can I get files from multiple folders in ASP.NET MVC?
public ActionResult DisplayFiles()
{
var getCategory = dbcontext.tblDetails.Select(x => x.Category).Distinct().ToList();
ViewBag.Category = getCategory;
foreach (string category in getCategory)
{
ViewBag.Images = Directory.EnumerateFiles(Server.MapPath("~/" + category)).Select(fn => "~/" + category + "/" + Path.GetFileName(fn));
}
return View();
}
I tried to upload it like this where category
returns the folder names from the database of table tblDetails
from where I want to get the files.我尝试像这样上传它,其中category
从我想要获取文件的表tblDetails
的数据库中返回文件夹名称。
Actually the above code overrides the folder name after every iteration of the loop and provides the last category name to the Viewbag.Images and only display the files of that folder实际上,上面的代码在每次循环迭代后覆盖文件夹名称,并将最后一个类别名称提供给Viewbag.Images并仅显示该文件夹的文件
Change your loop to something like: EDIT将您的循环更改为:编辑
List<string> images = new List<string>;
foreach (string category in getCategory)
{
images.AddRange(Directory.EnumerateFiles(Server.MapPath("~/" + category))
.Select(fn => "~/" + category + "/" + Path.GetFileName(fn)).ToList());
}
ViewBag.Images = images;
What you are doing in your loop is returning only the final image as the result will be over written on each iteration.您在循环中所做的只是返回最终图像,因为每次迭代都会覆盖结果。
Actually the above code overrides the folder name after every iteration of the loop and provides the last category name to the Viewbag.Images and only display the files of that folder实际上,上面的代码在每次循环迭代后覆盖文件夹名称,并将最后一个类别名称提供给 Viewbag.Images 并仅显示该文件夹的文件
You could try to use List<IEnumerable<string>>
to store all folders with their file names您可以尝试使用List<IEnumerable<string>>
来存储所有文件夹及其文件名
var data = new List<IEnumerable<string>>();
foreach (string category in getCategory)
{
var images = Directory.EnumerateFiles(Server.MapPath("~/" + category)).Select(fn => "~/" + category + "/" + Path.GetFileName(fn));
data.Add(images);
}
ViewBag.Images = data;
Then in your view, you could display them as a group like然后在您看来,您可以将它们显示为一个组,例如
@foreach( var folder in ViewBag.Images)
{
<ul>
@foreach (var image in folder)
{
<li>@image</li>
}
</ul>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.