January 2, 2009

How to use Eval on ImageUrl

Posted in ASP.NET tagged , , , , at 4:09 am by budi

I was converting the <img> into ASP.NET Image Control, I learnt new thing on the way.

Here is the code before I changed it:

<td>
  <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">
    <img height="140px" width="140px"
      src='images/catalog/<%# Eval("smallimageurl") %>' />
  </asp:HyperLink>
</td>

And I modified like so:

<td>
  <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">
    <asp:Image Height="140" Width="140" ID="Image4" runat="server"
      ImageUrl='~/images/catalog/<%# Eval("smallimageurl") %>' />
  </asp:HyperLink>
</td>

But the the Eval didn’t resolve correctly, here is the resulting HTML:

<img style="border-width: 0px; height: 140px; width: 140px;"
  src="../images/catalog/%3C%25#%20Eval(%22smallimageurl%22)%20%25%3E"
  id="ctl00_ContentPlaceHolder1_viewcategory1_DataList1_ctl00_Image4"/>

After doing some googling I found a solution to this.

The simple solution:

ImageUrl='<%# "~/images/catalog/" + Eval("smallimageurl") %>'

A more elegant solution:

ImageUrl='<%# Eval("smallimageurl", "~/images/catalog/{0}") %>'

And the correct HTML is:

<img style="border-width: 0px; height: 140px; width: 140px;"
  src="../images/catalog/MM54.jpg"
  id="ctl00_ContentPlaceHolder1_viewcategory1_DataList1_ctl00_Image4"/>

Follow

Get every new post delivered to your Inbox.