Dynammically Add Meta Tags and Java Script in ASP.NET 2.0 Content Page


One of the best features Microsoft added in ASP.NET 2.0 is the introduction of Master Pages. ASP.NET automatically add basic HTML mark up in the master page such as html, head, title and body tag and allows developers to add content pages of the website to fill content place holders in the Master Page. By using these basic HTML elements developers can add external CSS and Java Script files just once in Master Page and all the content pages get those files automatically.

Sometimes, developers need to inject CSS or Java Script dynamically for some specific ASP.NET pages. As head tag of html is not allowed in ASP.NET content pages so developers need to add these two files dynamically through C# or VB.NET code.

In the following tutorial I will show you how you can add Meta tags such as keywords or description and external Java Script file dynamically in ASP.NET 2.0 content page. 

Dynamically Adding Meta Tags

VB.NET

Dim keywordsTag As New HtmlMeta()
keywordsTag.Name = "keywords"
keywordsTag.Content = "Java, PHP, XML"
Me.Header.Controls.Add(keywordsTag)

Dim descriptionTag As New HtmlMeta
descriptionTag.Name = "description"
descriptionTag.Content = "For Latest Tutorials on Java, ASP.NET, C# Visit EzzyLearning.com"
Me.Header.Controls.Add(descriptionTag)

C#

HtmlMeta keywordsTag = new HtmlMeta(); 
keywordsTag.Name = "keywords"; 
keywordsTag.Content = "Java, PHP, XML"; 
this.Header.Controls.Add(keywordsTag); 
    
HtmlMeta descriptionTag = new HtmlMeta(); 
descriptionTag.Name = "description"; 
descriptionTag.Content = "For Latest Tutorials on Java, ASP.NET, C# Visit EzzyLearning.com"; 
this.Header.Controls.Add(descriptionTag);

Dynamically Adding External JavaScript Files

VB.NET

Dim externalJScript As New HtmlGenericControl()
externalJScript.TagName = "script"
externalJScript.Attributes.Add("type", "javascript")
externalJScript.Attributes.Add("src", "js/MyScript.js")
Me.Page.Header.Controls.Add(externalJScript)

C#

HtmlGenericControl externalJScript = new HtmlGenericControl(); 
externalJScript.TagName = "script"; 
externalJScript.Attributes.Add("type", "javascript"); 
externalJScript.Attributes.Add("src", "js/MyScript.js"); 
this.Page.Header.Controls.Add(externalJScript); 

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments