Binding Eval with an ImageURL in ASP.NET

2019-02-26 07:02发布

问题:

I'm trying to bind an image using Eval() with VB.NET and ASP.NET, but am running into issues:

Code snippet

<bri:ThumbViewer Id="Th1"  runat="server" 
   ImageUrl='<%# Eval("Name", "~/SiteImages/ram/3/{0}") %>' 
   Height="100px" 
   Width="100px" 
 />

I set strImagePath in the code-behind as:

strImagePath  ="~/SiteImages/ram/3/"

How can I replace:

~/SiteImages/ram/3/{0} 

with the variable strImagePath?

回答1:

simply use

<asp:Image id="abc" ImageUrl =<%# string.Format("~/SiteImages/ram/3/{0}",Eval("imagepath"))%>

imagepath could be from datatable or cs



回答2:

I personally prefer to do these things in the codebehind directly like

<bri:ThumbViewer ID="thumbViewer" runat="server" ... />

and then in the codebehind you have some initialize or DataBind() method where you write

thumbViewer.ImageUrl= Path.Combine(ImagePath, Name); //or something similar, you have to check

This because especially when you develop in a team it is quite inconvenient and error-prone if people do some bindings in the ASPX code directly using Eval(...) and some in the codebehind. I prefer using the codebehind because then you immediately see what's going on on the page by just looking on your code, while your ASPx code is just for layout, definition of controls (with properties) etc...



回答3:

string strImagePath = "aPage.aspx";
string pathFormat = "~/SiteImages/ram/3/{0}";
string path = String.Format(path, strImagePath);

Thats a little bit verbose, but you get the idea. What you're looking for is the String.Format method.

You can read more about it over at MSDN -> String.Format

So in your case that would be:

<bri:ThumbViewer Id="Th1"  runat="server" ImageUrl='<%# Eval("Name", String.Format("~/SiteImages/ram/3/{0}", strImagePath)) %>' Height="100px" Width="100px"/>

as long as strImagePath is set to public or protected in your codebehind



回答4:

Can you just write (and forgive me if this is wrong) if it is constant:

<bri:ThumbViewer ImageUrl='~/SiteImages/ram/3/<%# Eval("Name")%>' Height="100px" Width="100px" Id="Th1"  runat="server"/>

And if it isn't:

<bri:ThumbViewr ImageUrl='<#Eval("ImagePath + Name") %>' ... />

//And in your codebehid:
public property ImagePath { get; set; }
...
ImagePath = "...";