2012-09-24 105 views
2

我試圖從名稱圖像在項目目錄下創建的文件夾中顯示圖像。圖像沒有在運行時顯示

我正試圖訪問star.gif,它位於Images文件夾中。

這裏是我的一小段代碼,用於訪問圖像

TableCell tc=new TableCell();     

for (int j = 0; j < i; j++) 
{ 

    System.Web.UI.WebControls.Image rating = new System.Web.UI.WebControls.Image(); 
    rating.ImageUrl = Server.MapPath("~/Images/star.gif"); 
    rating.ID = j.ToString(); 
    rating.AlternateText = "No image"; 

    tc.Controls.Add(rating); 
} 

我甚至設置的授權在web.config,但沒有用它。

請在代碼中告訴我的錯誤。

+0

除非有特殊原因,否則,你不應該使用'使用Server.Mappath()'。嘗試檢查路徑以確保它指向正確的位置。 – Jeremy

回答

0

嘗試添加runat屬性,以便它從根解析?

rating.Attributes.Add("runat", "server"); 
rating.ImageUrl = "~/Images/star.gif"; 
4

只要刪除Server.MapPath。此呼叫將返回物理位置在您的服務器,這是無法在客戶端訪問!

MSDN使用Server.Mappath

MapPath方法映射到指定的相對或虛擬路徑 到服務器上相應的物理目錄。

新代碼

TableCell tc=new TableCell(); 
for (int j = 0; j < i; j++) 
{ 
    System.Web.UI.WebControls.Image rating = new System.Web.UI.WebControls.Image(); 
    rating.ImageUrl = "~/Images/star.gif"; // no need for Server.MapPath 
    rating.ID = j.ToString(); 
    rating.AlternateText = "No image"; 
    tc.Controls.Add(rating); 
} 
+0

謝謝。這解決了我的問題。 – codewarrior

+0

在這種情況下,請考慮投票我的答案和/或標記爲最佳答案! thx提前 –

1

Server.MapPath是要在服務器上,例如返回本地路徑C:\Images\star.gif。您的瀏覽器將無法解析該網址。

只需使用相對URL:

rating.ImageUrl = "~/Images/star.gif";