当我在后面的代码中设置带有URL的图像不起作用时,我不知道为什么?
if (File.Exists(Server.MapPath("~/Images/EmpQr/") + int.Parse(Session["userID"].ToString()) + ".PNG")) //It passes this condition
{
tr_res.Visible = true;
img_res.ImageUrl = Server.MapPath("~/Images/EmpQr/" + int.Parse(Session["userID"].ToString()) + ".PNG"); //Here 's the problem ,no image
}
else
{
tr_res.Visible = false;
}
<asp:Image ID="img_res" runat="server" AlternateText="result" />
当我像这样设置图像网址时
ImageUrl ="~/Images/EmpQr/1345.PNG"
在设计视图中它起作用。
如何解决这个问题?
Server.MapPath
为您提供文件的本地路径。而您真正想要的是相对于应用程序根路径(在服务器上!)的相对路径。为此,您已经拥有的~/Images/EmpQr/
文件就可以了,因此只需将文件名附加到该文件名即可:
img_res.ImageUrl = string.Format("{0}{1}.PNG", "~/Images/EmpQr/", int.Parse(Session["userID"].ToString()));
更新。出于好奇,在注释中进行了讨论之后,下面是Image
控制源代码的相关部分,该部分证明~/Images/...
可以正确处理形式的url :
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
string text = this.ImageUrl;
if (!this.UrlResolved)
{
text = base.ResolveClientUrl(text);
}
if (this.RenderingCompatibility >= VersionUtil.Framework45)
{
if (!string.IsNullOrEmpty(text) || base.DesignMode)
{
writer.AddAttribute(HtmlTextWriterAttribute.Src, text);
}
}
else
{
if (text.Length > 0 || !base.EnableLegacyRendering)
{
writer.AddAttribute(HtmlTextWriterAttribute.Src, text);
}
}
//...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句