在不同目录级调用图片路径问题
有时我们会遇到在不同目录层次下的文件调用一个公共方法,这个公共方法是用于取得图片路径。这时就会出现图片路径不对。导致图片无法显示。
解决方法:
1.可以用Page.Request.ApplicationPath获取URL的根路径。例如:stirng ImgUrl=string.Concat(Request.ApplicationPath,"/images/banner.gif");
2.ResolveUrl方法:
获取URL客户端路径
例子1:
.aspx页面
<asp:Image ID="Image1" runat="server" />
.cs页面
this.Image1.ImageUrl = ResolveUrl("~/images/ad/xhx3.jpg");
例子2:
<img src='<%= ResolveUrl("~/images/top.gif") %>' border="0" />
扩展方法:
.aspx页面
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
.cs页面
StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
obj.RenderControl(writer);
Literal1.Text = sw.ToString();
实体类
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
/// Summary description for MyResolveUrl
/// </summary>
public class MyResolveUrl:Control
{
public MyResolveUrl()
{
//
// TODO: Add constructor logic here
//
}
private string _ImageUrl;
public string ImageUrl
{
get
{
return _ImageUrl;
}
set
{
_ImageUrl = value;
}
}
protected override void Render(HtmlTextWriter output)
{
Image myImage = new Image();
// Resolve Url.
myImage.ImageUrl = ResolveUrl(this.ImageUrl);
myImage.RenderControl(output);
}
}
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
.cs页面
StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
obj.RenderControl(writer);
Literal1.Text = sw.ToString();
实体类
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
/// Summary description for MyResolveUrl
/// </summary>
public class MyResolveUrl:Control
{
public MyResolveUrl()
{
//
// TODO: Add constructor logic here
//
}
private string _ImageUrl;
public string ImageUrl
{
get
{
return _ImageUrl;
}
set
{
_ImageUrl = value;
}
}
protected override void Render(HtmlTextWriter output)
{
Image myImage = new Image();
// Resolve Url.
myImage.ImageUrl = ResolveUrl(this.ImageUrl);
myImage.RenderControl(output);
}
}
3.TemplateSourceDirectory 有兴趣的可以查MSDN.