Home ยป Technology | Useful tips

Adding Meta tags at runtime or dynamically in asp.net master and content pages

  23. May 2010 by Soan

Asp.net is well known for its Master page and Content page architecture to support code re-usability.
Recently, I was trying to place the TITLE and META tags on master page and then setting their values at runtime (dynamically ) using the code behind of the respective content page.

In my Master page, I had written the HEAD tag as follows:

I was easily able to set the title of the page using content page's code behind like this:

Page.Title = "My page's Title" ;

This worked like a charm but the problem appeared with META tags. There is no such object available at page level to directly access the Meta tag. Hence, I looked around for a workaround and found many approaches to solve the issue. The best and easiest one is the following which i actually used in my code:

Created the following HEAD tag in my master page (Basically removed the META tag as we are going to add it at runtime using code-behind):

And then added the following code (C#) in my page's code-behind file to set the META tag at runtime. This process actually creates new objects of META tag and then adds them to the HEAD tag at runtime.

For using the code you would also need to include the following .net library:

using System.Web.UI.HtmlControls;

/****************** Add META tags - start***************************/
HtmlMeta metaTagDesc = new HtmlMeta(); //Create a new instance of META tag object
HtmlMeta metaTagKeywords = new HtmlMeta();

metaTagDesc.Attributes.Add("name", "description"); // Add attributes to the META tag object for identification
metaTagDesc.Attributes.Add("content", "YOUR META DESCRIPTION HERE" );

metaTagKeywords.Attributes.Add("name", "keywords");
metaTagKeywords.Attributes.Add("content", "YOUR META KEYWORDS HERE" );

Page.Header.Controls.Add(metaTagDesc);
//Add the meta tags to head tag of current page. Page.Header.Controls.Add(metaTagKeywords);
/****************** Add META tags - END***************************/

Using the above method, you can create separate meta description and keyword for each page and build better ranking in search engines.

TITLE, META DESCRIPTION AND META KEYWORDS are used by search engines to understand the content of web pages and rank accordingly in the search results.

Search engines do not list all pages from a website, they only index pages with good unique content based on the above mentioned tags.

Related: You actually do not search whole internet with Google

Would you like to share this article?

QR Code for this page Scan this QR code to open this
article in any mobile browser
or share with friends.


For more helpful articles like this, subscribe to our free newsletter or stay connected on social networks:

SUBSCRIBE
Subscribe to AM22 tech in Reader or by Email
Sign up for our updates in Email (Free):

 

Have questions? Write into comments or ask in forum