从数据库中获取图片并将其绑定到ListView

时间:2015-07-30 22:49:14

标签: c# asp.net listview itemdatabound

我很抱歉这个问题因为我认为它可能非常基本,但我似乎遇到了很多麻烦。

我要做的是获取我保存在数据库中的图片并将其绑定到我拥有的ListView。

在数据库中我没有图片本身,我有图片的名称,所以我想尝试使用它的PathWay获取它。

我正在使用ASP.NET Web窗体网站 这是ListView,因此您可以更好地理解我的意思

<asp:ListView runat="server" ID="lvBrands" OnItemDataBound="lvBrands_ItemDataBound">
                <LayoutTemplate>
                    <ul class="grid portfolio isotope no-transition portfolio-hex portfolio-shadows row demo-3 os-animation" data-os-animation="fadeInUp">
                        <li runat="server" id="itemPlaceholder"></li>
                    </ul>
                </LayoutTemplate>
                <ItemTemplate>
                    <li class="portfolio-item col-md-3 col-sm-3 style fashion grid cs-style-3">
                        <figure class="portfolio-figure">
                            <img src="images/products/test.jpg" alt="work-01" />
                            <figcaption>
                                <h4 class="title purpleColored" color="#58387B"><%# Eval("name") %></h4>
                                <span><%# Eval("keyword") %></span> <a class="text-right" href="javascript:;"><i class="fa fa-angle-right"></i></a>
                            </figcaption>
                        </figure>
                    </li>
                </ItemTemplate>
            </asp:ListView>

而不是<img src=... />我想要附加图片路径,以便它可以显示适当品牌的合适图片。

品牌是我在sql中创建的一个表,基本上品牌和图片之间的关系是一对多的(一个品牌可以有很多图片)

在我到目前为止搜索过的内容中,我发现最好使用OnItemDataBound从数据库中获取图片,任何进一步的帮助都会非常感激。

以下是进一步帮助的c#代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DisplayBrands();
        }
    }
    protected void DisplayBrands()
    {
        using (Entities db = new Entities())
        {
            List<Brand> brand = db.Brands.ToList();
            lvBrands.DataSource = brand.OrderByDescending(b => b.date_created);
            lvBrands.DataBind();
        }
    }

}

我知道我应该指定函数lvBrands_ItemDataBound,但老实说我不知道​​要添加什么。

任何帮助都会很棒, 谢谢!

1 个答案:

答案 0 :(得分:0)

<img src="images/products/test.jpg" alt="work-01" />

如上所述更改

<img src='<%# @"images/products/" + Eval("Image_name") %>' alt="work-01" />

&#34;的 IMAGE_NAME &#34;应该是列的名称,您可以在其中存储图片名称。