0

我想在我的 asp.net 网页上显示图像列表。图片位于文件夹中。我的 aspx 代码看起来像这样

   <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();
 }

问题是 img 标签的 src 属性需要相对路径,就像localhost/images... 现在我得到类似的东西: C:\Inetpub\wwwroot\images\image1.jpg

4

3 回答 3

2

You can use:

pathForPictures.Add(
    Page.ResolveClientUrl(
        System.IO.Path.Combine(
            "~/images/",
            System.IO.Path.GetFileName(PP)
        )
    )
);

Or instead of doing a loop:

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();
}
于 2013-08-19T17:35:20.600 回答
1

利用ResolveUrl

试试这个代码

this.ResolveUrl("~/images/")

代替

Server.MapPath("~/images/");

或者干脆试试ResolveUrl("~/images/")

更多详细信息,请参阅路径的这个很好的解释

于 2013-08-19T17:39:05.983 回答
1

尝试 Page.ResolveUrl 而不是 Server.MapPath

于 2013-08-19T17:24:52.937 回答