0

我只想根據asp.net網站中ComboBox中選定的索引更改我的面板背景圖像。但圖像不加載。這是我在.aspx頁面中如何將asp.net中的圖片更改爲組合框選定的索引更改

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" 
    onselectedindexchanged="DropDownList1_SelectedIndexChanged"> 
    <asp:ListItem>1</asp:ListItem> 
    <asp:ListItem>2</asp:ListItem> 
    <asp:ListItem>3</asp:ListItem> 
</asp:DropDownList> 

<div id="divx" style="height: 250px"> 
    <asp:Panel ID="Panel1" runat="server" Height="242px"> 
    </asp:Panel> 
</div> 

代碼而這背後是代碼..

protected void Page_Load(object sender, EventArgs e) 
{ } 
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (DropDownList1.SelectedIndex == 1) 
    { 
     Panel1.BackImageUrl="C:\\Users\\Laksh\\Documents\\Visual Studio 2010\\WebSites\\WebSite2\\Pic\\Capture.JPG"; 
    } 
    else if (DropDownList1.SelectedIndex == 2) 
    { 
     Panel1.BackImageUrl="C:\\Users\\Laksh\\Documents\\Visual Studio 2010\\WebSites\\WebSite2\\Pic\\erroe.JPG"; 
    } 
} 
+1

你有沒有想過使用Server.MapPath 「../Pic/Capture.JPG」);獲取圖像的文件路徑名? – KingPancake

+0

是的,我試過先生..但它給了一個例外... 'C:/用戶/ Laksh /文件/ Visual Studio 2010/WebSites/WebSite2/Pic/Capture.JPG'是一個物理路徑,但一個虛擬路徑預計將會出現。' – tharindlaksh

+0

什麼是例外? – KingPancake

回答

2

這是不可能設置一個aboslute路徑,指的是一個位置,你的本地磁盤上!這導致了這樣的代碼......

<!-- This imageURL won't work!! --> 
<div id="Panel1" style="height:250px;background-image:url(c:%09emp%0demo.jpg);">  
</div> 

使用相對路徑,而不是!

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    Panel1.BackImageUrl = "~/pic/error.jpg"; 
} 

如果你不知道該怎麼做,你可以總是將backgroundImage指定使用您的aspx頁面的設計視圖的面板。只需選擇面板,去屬性,點擊屬性BackImageUrl您的項目中選擇圖像。 VS將爲您的圖像添加完美的工作路徑!

+0

這應該工作,但我不認爲回發方法是理想的。用戶體驗很糟糕。考慮註冊客戶端(JS)on-change事件以避免每次用戶在項目之間切換時需要回發。 –

+0

當然這會更好,但由於autoPostBack在原始問題中,我沒有改變這個細節。但隨意發表一個例子,所以我/我們可以學習它! thx –

+0

但這種方法也不工作..先生...它力量給任何例外..但不是加載圖像.. – tharindlaksh

0

我同意@Pilgerstorfer Franz,使用相對路徑即〜/ xyz ...並執行server.mappath。通常,Web服務器對服務器目錄級別以外的本地計算機沒有權限,所以直接映射不是一個好主意。

您也可以嘗試使用jQuery來進行更改,您可以嘗試下面的方法。你需要讓它從你的ddl中取得你的值,但你可以將它傳遞給你的函數,或者讓它參考ddl的值字段也許...

<html> 
    <head> 
     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" ></script> 
     <script> 
      function doIt() 
      { 
       $('#divTryMe').css('background-image','url("test.jpg")'); 
      } 
     </script> 
    </head> 
    <body> 
     <div id="divTryMe" onclick="doIt()">stuff</div> 
    </body> 
</html> 
相關問題