Michael
Michael

Reputation: 339

ASP.NET dynamic image url using server tags

I am trying to set the ImageUrl using the following code...

<asp:Image ID="brokenImage" runat="server" AlternateText="Coded path" ImageUrl='~/headerImages/<%= getImage(Request.QueryString["Id"]) %>'/>

Eliminating the opening tag and viewing the browser ouput alongside an image tag that is explicitly written produces the following results....

asp:Image ID="brokenImage" runat="server" AlternateText="Coded path" ImageUrl='~/headerImages/images (3).jpg' />

asp:Image ID="workingImage" runat="server" AlternateText="Explicit Path" ImageUrl="~/headerImages/images (3).jpg" /> 

Why is the first image not displaying but the second is? How can I pass a parameter to the code behind and set the url?

Upvotes: 1

Views: 9521

Answers (1)

afzalulh
afzalulh

Reputation: 7943

If you are looking for correct way to do this, your markup should be :

<asp:Image ID="brokenImage" runat="server" AlternateText="Coded path" ImageUrl='<%# "~/headerImages/" + getImage(Request.QueryString["Id"]) %>'/>

And in the code you should have this:

brokenImage.DataBind();

Explanation: <%= %> outputs directly to the response stream. And <%# %> evaluates the code when you bind the control. Very nice and short explanation here.

Upvotes: 3

Related Questions