2009-09-20 95 views
0

我一直在努力尋找一些方法來做我需要的條件綁定。有條件的數據綁定困難

我想在條件綁定中使用Eval("products_image"),這樣,如果product_image存在於images目錄中,那麼它是可以的,否則它應該顯示「noimage.jpg」。

我試圖做這樣說:

<%# (File.Exists(("ProductImages/"+Convert.ToString(Eval("products_image"))))) ? ("ProductImages/"+Convert.ToString(Eval("products_image"))) : "ProductImages/noimage_small.jpg" ; %> 

我曾嘗試其他方法爲好,但每一次,我惹了一堆錯誤。

任何人都可以指導我做到這一點的正確方法嗎?

回答

1
<%# (File.Exists(("ProductImages/"+Convert.ToString(Eval("products_image"))))) ? ("ProductImages/"+Convert.ToString(Eval("products_image"))) : "ProductImages/noimage_small.jpg" ; %> 

很長且難以理解,不是嗎?

我建議增加一個方法後面的代碼或在<script>標籤

// returns the imageFile parameter if the file exists, the defaultFile parameter otherwise 
string ImageFileExists(string imageFile, string defaultFile) { 
    if (File.Exists(Server.MapPath(imageFile))) 
     return imageFile; 
    else 
     return defaultFile; 
} 

然後你只需使用

<%# ImageFileExists("ProductImages/" + Eval("products_image").ToString(), "ProductImages/noimage_small.jpg") %> 

請注意,我添加了一個Server.MapPath通話該方法使File.Exists實際上看起來在正確的地方。

+0

+1:廢話,你打我吧。並有一個非常整潔的解決方案。 :) – 2009-09-20 03:21:09

+0

是的,這是偉大的。我在我的母版頁中添加了

0

我剛剛在usercontrol .ascx文件本身內部移動了整個<script>標記和System.IO命名空間,並且它做到了。

由於一噸配置用於幫助:)