asp.netmaster-pagestitlemetatag

How can I add title and meta tags for content pages in a project based on master and content pages (dynamically)


How can I add title and meta tags for content pages in a project based on master and content pages (dynamically) ?

I used the below method for master page :

public void SetMetaTags(string title, string description, string keywords)
{

    // Get a reference to the HTML Head
    HtmlHead headTag = (HtmlHead)Page.Header;

    // Set the page title
    headTag.Title = title;

    // Add a Description meta tag
    HtmlMeta metaTag = new HtmlMeta();
    metaTag.Name = "Description";
    metaTag.Content = description;
    headTag.Controls.Add(metaTag);

    // Add a Keywords meta tag
    metaTag = new HtmlMeta();
    metaTag.Name = "Keywords";
    metaTag.Content = keywords;
    headTag.Controls.Add(metaTag);
}

so I don't know why the following code in Page_Load of Content Page has an error:

protected void Page_Load(object sender, EventArgs e)
{
    MasterPage MyMasterPage = (MasterPage)Master;

    // Error on this line:
    MyMasterPage.SetMetaTags("Title", "description", "keywords");
}

and the error is:

Error 17 'System.Web.UI.MasterPage' does not contain a definition for 
'SetMetaTags' and no extension method 'SetMetaTags' accepting a first argument of
type 'System.Web.UI.MasterPage' could be found (are you missing a using directive
or an assembly reference?)
C:\Javad\---\AlmasAfzar\AlmasAfzar\AlmasAfzar\Products.aspx.cs  16  26
AlmasAfzar

Thanks in future advance

best regards


Solution

  • You need to cast the type returned from Page.Master to be the type of your master page, not System.Web.UI.MasterPage.

    So, if your master page class with the SetMetaTags method is named MasterWithMetaTags, your Page_Load code needs to look like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        MasterWithMetaTags MyMasterPage = (MasterWithMetaTags)Master;
        MyMasterPage.SetMetaTags("Title", "description", "keywords"); 
    }