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


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

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


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

Dynamically Adding External JavaScript Files


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


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



About author

User avatar

Waqas Anwar

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