Server controls like Image.ImageUrl make this very easy, but trying to achieve the same thing in code behind to an IMG html control is not that straightforward.
For example using an Asp:Image server control and setting ImageUrl property to “~/Images/Test.jpg” works fine no matter what directory i place the code in. (asp.net transforms tilde directory to relative)
How can i do the same in code behind? when i am trying to create an HTML IMG control?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use Page.ResolveUrl(“~/…..”);
Method 2
In the template:
<img id="imgTest" runat="server" />
In the codebehind:
imgTest.Attributes["src"] = this.ResolveUrl("~/yourimage.gif");
Does this solve your problem? Not really sure why you’re not using an asp:image control…
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0