我正在使用 Razor MVC,我想显示来自“~/Content/uploads”文件夹的图像。
我想出了以下解决方案:
@foreach (FileInfo fileInfo in (new DirectoryInfo(Server.MapPath("~/Content/uploads"))
.GetFiles().Where(x => x.Extension == ".jpg"))) {
<img src="/@fileInfo
.FullName
.Substring(Server.MapPath("~/").Length)
.Replace("\\", "/")"
width="100">
}
代码的问题是我正在使用完整的文件路径
我正在删除 Server.MapPath() 前缀。
如何简化此代码?
最佳答案
您可以使用 UrlHelper Razor 页面上可用的类。
@foreach (var imgPath in Directory.GetFiles(Server.MapPath("~/Content/uploads"), "*.jpg"))
{
var img = new FileInfo(imgPath);
<img src="@Url.Content(String.Format("~/Content/uploads/{0}", img.Name))" />
}
关于asp.net-mvc-4 - 如何使用 Razor MVC 显示文件夹中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21659134/