Ran into a scenario today where I needed to add a base tag to my page. Couldn't find a clean way to do it with the stock asp.net controls, so created a couple quickies:
public class HtmlEmptyControl : HtmlControl {
protected override void Render(HtmlTextWriter writer) {
writer.WriteBeginTag(this.TagName);
this.RenderAttributes(writer);
writer.Write(" />");
}
}
Very simple, just renders an empty element (self closing tag). Code there is borrowed from the HtmlLink control.
public class HtmlBase : HtmlEmptyControl {
public override string TagName {
get {
return "base";
}
}
public string Href { get; set; }
public string Target { get; set; }
protected override void OnInit(EventArgs e) {
Uri requestUri = Page.Request.Url;
string relativePath = Page.Request.CurrentExecutionFilePath;
string relativeRoot = VirtualPathUtility.GetDirectory(relativePath);
UriBuilder baseUri = new UriBuilder() {
Scheme = requestUri.Scheme,
Host = requestUri.Host,
Port = requestUri.Port,
Path = VirtualPathUtility.AppendTrailingSlash(relativeRoot)
};
this.Href = baseUri.ToString();
base.OnInit(e);
}
protected override void RenderAttributes(HtmlTextWriter writer) {
if (!string.IsNullOrEmpty(this.Href))
this.Attributes.Add("href", this.Href);
if (!string.IsNullOrEmpty(this.Target))
this.Attributes.Add("target", this.Target);
base.RenderAttributes(writer);
}
}
A self initializing base tag. Usage like so:
this.Page.Header.Controls.AddAt(0, new HtmlBase());
Which I just threw in my Master Page's OnPreRender. This is useful for cases where the request's PathInfo starts with a / (i.e. page.aspx/foo/bar).
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5