Craig Gibbons' Lifeblog lifeblog://tri.eat.net

23Aug/060

Adding META, CSS, JavaScript or any other kind of tag to a Page or MasterPage header

In .NET there is always a way. As far as I can tell, after working
extensively with the Framework for about 4 years, nothing has been
omitted. One might encounter the odd anomaly, but for the most part
there is always several workarounds to any problem which may arise.
Working with MasterPages poses some of its own problems. One such
problem is the adding of tags to the Page header. Such tags include
META, CSS and JavaScript, but this could be anything defined by the
standard. The tags can of course be entered straight into the page
code, but if you want to conditionally include something or use a
virtual path, you need to do this programmatically. The following three
code snippets show how to add META, CSS and any other tag to the Page
header.

META Tags

protected void Page_Load(object sender, System.EventArgs e) {
    HtmlMeta meta = new HtmlMeta();
    meta.HttpEquiv = "refresh";
    meta.Content = "5;http://www.gibbons.co.za";
    Page.Header.Controls.Add(meta);
}

CSS Tags

protected void Page_Load(object sender, System.EventArgs e) {
    HtmlLink css = new HtmlLink()
    css.Href = "http://www.gibbons.co.za/Style.css";
    css.Attributes["rel"] = "stylesheet";
    css.Attributes["type"] = "text/css";
    Page.Header.Controls.Add(css);
}

Any other tag (e.g. JavaScript include)

protected void Page_Load(object sender, System.EventArgs e) {
    HtmlGenericControl control = new HtmlGenericControl("script");
    control.Attributes["src"] = "common.js";
    control.Attributes["type"] = "text/javascript";
    control.Attributes["language"] = "javascript";
    Page.Header.Controls.Add(control);
}

Alternatively, you can always use a HtmlGenericControl and use the Attributes collection to write any attributes you desire.

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.