Dynamically changing META Tags in MasterPages from ContentPage
The earlier method doesn't work in some cases so I was looking for some proper method.
And finally I have found another method of changing meta tag values.
You can visit the following website that describes the content with proper example.
http://www.aspnettutorials.com/tutorials/performance/metatags-csharp.aspx
Abstracts:
Firstly, on our MasterPage, we give our meta tags and the page title an ID, and runat attribute:
<title id="PageTitle" runat="server">This is the Default Page Title...</title> <meta name="Keywords" id="PageKeywords" content="default, page, keywords" runat="server" /> <meta name="Description" id="PageDescription" content="This is the Default page desctription, which should be changed when the page is loaded." runat="server" /> |
Next, we put the following code in MasterPage code-behind:
public string MetaTitle
{
get
}{
return PageTitle.Text;
}set {
PageTitle.Text = value;
}public string MetaKeywords {
get
}{
return PageKeywords.Content;
}set {
PageKeywords.Content = value;
}public string MetaDescription {
get
}{
return PageDescription.Content;
}set {
PageDescription.Content = value;
} |
The Default.aspx (content page) looks like the following:
<%@
Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
Upon loading of this page, the new Page
Title, Description and Keywords meta tags should be displayed. You can
check this by viewing the browser window title.<br />
</asp:Content> <br /> This small area of the page is a content page, the background is the master page. |
Then in the code-behind of Default.aspx we have the following, which will set the meta tags:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
} {
MasterPage myMaster = (MasterPage)this.Master;
}myMaster.MetaTitle = "This is the new Page Title, which is set upon Page_Load"; myMaster.MetaDescription = "This is the new Page Description, which is set upon Page_Load"; myMaster.MetaKeywords = "new, page, keywords, set, upon, page, load"; |
AlpesH Shah
No comments:
Post a Comment