【问题标题】:Difficulty with conditional databinding条件数据绑定的困难
【发布时间】:2010-11-29 19:50:29
【问题描述】:

我一直在努力寻找某种方法来完成我所需的条件绑定。

我想在条件绑定中使用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" ; %>

我也尝试过其他方法,但每次都搞砸了一堆错误。

谁能指导我正确的做法?

【问题讨论】:

    标签: c# asp.net data-binding binding conditional


    【解决方案1】:
    <%# (File.Exists(("ProductImages/"+Convert.ToString(Eval("products_image"))))) ? ("ProductImages/"+Convert.ToString(Eval("products_image"))) : "ProductImages/noimage_small.jpg" ; %>
    

    相当长且难以阅读,不是吗?

    我建议在您的代码后面或&lt;script&gt; 标记中添加一个方法

    // 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 实际上会在正确的位置查找。

    【讨论】:

    • +1:废话,你打败了我。还有一个非常简洁的解决方案。 :)
    • 是的,这很棒。我在我的母版页内的
    • 我认为你的脚本标签中缺少一个 runat="server"... 你放了一个吗?
    • 是的,它不见了,我已经把它放在那里了。但它仍然是错误的。 CS0103:当前上下文中不存在名称“ImageFileExists”。在 .ascx 文件中使用它有什么不同的方法吗?
    【解决方案2】:

    我刚刚将整个 &lt;script&gt; 标记和 System.IO 命名空间移到了 usercontrol .ascx 文件本身中,它确实做到了。

    非常感谢配置器的帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      相关资源
      最近更新 更多