HTML img and ASP.NET Image and relative paths

こ雲淡風輕ζ 提交于 2019-11-27 06:38:33

问题


What is the correct way to reference an image in ASP.NET for live deployment on IIS?

The following works in dev and production:

<asp:ImageButton ID="ibnEdit" runat="server" OnClick="ibnEdit_Click" ImageUrl="~/App_Themes/Default/images/one.png" Visible="false" ToolTip="Edit" />

The following doesn't work in either: (why not?)

<img src="~/App_Themes/Default/images/two.gif" />

The following works in dev but not in production:

<img src="../App_Themes/Default/images/two.gif" />

回答1:


If you want to use a regular img tag with the ~ path, you can just add runat="server" into the tag as an attribute (like regular server controls) and the path will be resolved. e.g:

<img src="~/App_Themes/Default/images/two.gif" runat="server" /> 

For your second part, is the ../ image reference appearing on more than one page, for example a user control or master page (etc) such that you might be using it at different folder levels...




回答2:


I use this syntax for access images from master pages

<img src="<%=ResolveUrl("~/Content/Images/error_img.jp")%>" width="350" style="padding-right: 15px; padding-top: 20px;"/>



回答3:


The ~ will only work on a server control such as or . This tells ASP.Net to insert the application path. Sometime that's just "/" but if your application is not the root directory of the website it will include the path it is in. The img tag is just html and it will not be altered by ASP.Net, so the browser gets the path "~/App_Themes/Default/images/two.gif" and doesn't know how to read it.

I don't know why the last example works in dev but not in production. It might has something to do with having the application in the root directory in dev but in a sub directory in production.




回答4:


This worked for me

$(".selector").attr('src', "Content/themes/base/images/img.png");

The important is that you do not have "/" at the beginning of your new src.




回答5:


byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));

string base64ImageRepresentation = Convert.ToBase64String(imageArray);


来源:https://stackoverflow.com/questions/5190769/html-img-and-asp-net-image-and-relative-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!