Asp.net 如何为src属性获取图像的相对路径
我想在我的asp.net网页上显示图像列表。 图片位于文件夹中。 我的aspx代码如下所示Asp.net 如何为src属性获取图像的相对路径,asp.net,path,Asp.net,Path,我想在我的asp.net网页上显示图像列表。 图片位于文件夹中。 我的aspx代码如下所示 <asp:ListView runat="server" ID="lvPicturePaths"> <ItemTemplate> <img src="<%# Container.DataItem %>" /> </ItemTemplate> </ListView> " /> 在代码隐藏中,我有
<asp:ListView runat="server" ID="lvPicturePaths">
<ItemTemplate>
<img src="<%# Container.DataItem %>" />
</ItemTemplate>
</ListView>
" />
在代码隐藏中,我有:
private void GetImagePaths()
{
List<string> pathForPictures=new List<string>();
var path=Server.MapPath("~/images/");
foreach(var PP in Directory.GetFiles(path))
{
pathForPictures.Add(PP);
}
lvPicturePaths.DataSource=pathForPictures;
lvPicturePath.DataBind();
}
private void getimagepath()
{
List pathForPictures=新列表();
var path=Server.MapPath(“~/images/”);
foreach(Directory.GetFiles(path)中的var PP)
{
pathForPictures.Add(PP);
}
lvPicturePath.DataSource=pathForPictures;
lvPicturePath.DataBind();
}
问题是img标记的src属性需要相对路径,比如localhost/images…
现在我得到了这样的结果:
C:\Inetpub\wwwroot\images\image1.jpg
尝试Page.ResolveUrl而不是Server.MapPath尝试Page.ResolveUrl而不是Server.MapPath您可以使用:
pathForPictures.Add(
Page.ResolveClientUrl(
System.IO.Path.Combine(
"~/images/",
System.IO.Path.GetFileName(PP)
)
)
);
或者不做循环:
private void GetImagePaths()
{
const string path = "~/images/";
var pictures =
Directory.GetFiles(Server.MapPath(path))
.Select(p =>
Page.ResolveClientUrl(Path.Combine(path, Path.GetFileName(p))));
lvPicturePaths.DataSource = pictures;
lvPicturePath.DataBind();
}
您可以使用:
pathForPictures.Add(
Page.ResolveClientUrl(
System.IO.Path.Combine(
"~/images/",
System.IO.Path.GetFileName(PP)
)
)
);
或者不做循环:
private void GetImagePaths()
{
const string path = "~/images/";
var pictures =
Directory.GetFiles(Server.MapPath(path))
.Select(p =>
Page.ResolveClientUrl(Path.Combine(path, Path.GetFileName(p))));
lvPicturePaths.DataSource = pictures;
lvPicturePath.DataBind();
}
使用
ResolveUrl
试试这个代码
this.ResolveUrl("~/images/")
而不是
Server.MapPath("~/images/");
或者只需尝试ResolveUrl(“~/images/”)
有关更多详细信息,请参阅这篇关于使用解析URL的好解释 试试这个代码
this.ResolveUrl("~/images/")
而不是
Server.MapPath("~/images/");
或者只需尝试ResolveUrl(“~/images/”)
更多详细信息,请参见此说明,仅FYI-GetImagePaths无法获取图像路径。也许您应该将其重命名为BindPicturePath,或者让其返回IEnumerable并将其绑定到其他位置?仅FYI-GetImagePaths无法获取图像路径。也许您应该将其重命名为BindPicturePath,或者让其返回IEn把它绑在别的地方?