German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Update Header Dynamically in ASP.NET 2.0

Written by omerkamal on Jul 22, 2007
Custom header elements in ASP.NET Pages

Explanation:

Add Javascript files to the Header
HtmlGenericControl si = new HtmlGenericControl();
si.TagName = "script";
si.Attributes.Add("type", "javascript");
si.Attributes.Add("src", "/file.js");
this.Page.Header.Controls.Add(si);

If you happen to use getElementById("tagName") in javascript code, it works fine with stand alone aspx page but need to modifiy little bit in master/content page. Change it to getElementById("<%=tagName.ClientID %>")

Also, if the javascript referred to a filed name inside FormView. We need to specify the form filed in page_load event. Example:

TextBox TextBox1 = FormView1.FindControl("TextBox1") as TextBox;

Now, you can manipulate the TextBox1

Add External Style Sheet to the Header
HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", "~/main.css");
this.Header.Controls.Add(link);


Add Style attribute for the Page
Style style = new Style();
style.ForeColor = System.Drawing.Color.Navy;
style.BackColor = System.Drawing.Color.LightGray;
this.Header.StyleSheet.CreateStyleRule(style, null, "body");

Add Dynamic Meta tags to the Header
HtmlMeta meta = new HtmlMeta();
meta.Name = "keywords";
meta.Content = "Your keywords here";
this.Header.Controls.Add(meta);

meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex";
this.Header.Controls.Add(meta);

meta = new HtmlMeta();
meta.Name = "date";
meta.Content = DateTime.Now.ToString("yyyy-MM-dd");
meta.Scheme = "YYYY-MM-DD";
this.Header.Controls.Add(meta);

Add Updated Page title to the Page
this.Header.Title = "Sue's little edream share with the world";

Also, use sitemap note for your title is a nice option:

Add Page title from the SiteMap Current Node
this.Header.Title =  SiteMap.CurrentNode.Title + " | " + SiteMap.CurrentNode.Description;

Note: All the above code should be used within page Page_Load event.

Visitors/Readers Comments
(for questions please use The Forum)



Paneque
nice code, very usefull, simple but usefull, thanks, it helped me.

27/08/2007 04:48:11 UTC

_Ehecatl
Excelent sample... Very useful for me...

06/11/2007 20:46:12 UTC

vv
beautiful !!!

31/01/2008 16:20:45 UTC

Bruce
Just what I needed

18/09/2008 15:04:22 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)