Tuesday 6 May 2014

How to generate dynamic meta tags?


If we want to add Meta tags statically we will set like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add meta tags dynamically to aspx page in asp.net</title>
<meta name="description" content="Aspdotnet-Suresh offers Asp.net,C#.net,SQL Server,Web Services,Ajax,JavaScript,JQuery,Gridview articles and examples" />
<meta name="keywords" content="asp.net,C#.NET,suresh dasari,GridView,DropDownList,,JavaScript,JQuery,XML" />
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Aspdotnet-Suresh.com Meta Tags Example</b>
</div>
</form>
</body>
</html>
If we want to add Meta tags dynamically to aspx page we need to write the code like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Aspdotnet-Suresh.com Meta Tags Example</b>
</div>
</form>
</body>
</html>
After that open code behind page and add the following namespace references


using System;
using System.Web.UI.HtmlControls;
After add namespaces write the following code in code behind

C# code


protected void Page_Load(object sender, EventArgs e)
{
// set page title
Page.Title = "Add meta tags dynamically to aspx page in asp.net";
//Page description
HtmlMeta pagedesc = new HtmlMeta();
pagedesc.Name = "Description";
pagedesc.Content =
"Aspdotnet-Suresh offers Asp.net,C#.net,SQL Server,Web Services,Ajax,JavaScript,JQuery,Gridview articles and examples";
Header.Controls.Add(pagedesc);
//page keywords
HtmlMeta pagekeywords = new HtmlMeta();
pagekeywords.Name = "keywords";
pagekeywords.Content = "asp.net,C#.NET,suresh dasari,GridView,DropDownList,,JavaScript,JQuery,XML";
Header.Controls.Add(pagekeywords);
}
VB.NET Code


Partial Class VBSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
' set page title
Page.Title = "Add meta tags dynamically to aspx page in asp.net"
'Page description
Dim pagedesc As New HtmlMeta()
pagedesc.Name = "Description"
pagedesc.Content = "Aspdotnet-Suresh offers Asp.net,C#.net,SQL Server,Web Services,Ajax,JavaScript,JQuery,Gridview articles and examples"
Header.Controls.Add(pagedesc)
'page keywords
Dim pagekeywords As New HtmlMeta()
pagekeywords.Name = "keywords"
pagekeywords.Content = "asp.net,C#.NET,suresh dasari,GridView,DropDownList,,JavaScript,JQuery,XML"
Header.Controls.Add(pagekeywords)
End Sub

End Class
If you want to see output run above code snippet and Right click on your page and select view sourcein that check for title, description and keywords that would be like this

Demo


No comments:

Post a Comment