Saturday, 10 September 2016

ASP.NET - Setting HTML Meta tags in content pages

Problem:


Though the @Page directive in a content page allows one to specify the Description and Keywords attrubutes, the same is ignored when the page is rendered. Instead the Description and Keywords as specified in the master page is what gets rendered as part of the final html output. Is this the intended design and is there a solution to work around this issue?


Solution:


By design, the HTML Meta tags specified in the content page is ignored when the page is rendered. In this context it is important to understand the following:

  • The Master page contains the <head> tag of the page and not the content page. As such the meta tags specified in the master page will prevail.
  • The Content page derives the System.Web.UI.Page class, which though recognizes the Title attribute provided as part of the @Page directive, it does not recognize the other meta tags like description and keywords.
  • The master page and content page are dendered in teh following order:
    • Content Page PreInit event
    • Master Page Init event
    • Content Page Init event
    • Content Page Load event
    • Master Page Load event

As you may observe, while the Load event of Master page happens after that of the Content Page, the Init event of the Master page happens ahead that of the content page.  Given that the Master page loads after the content page, you can manage to use the Title attribute specified in the content page using the script tag within the <title> element, as below:

<title><%: Page.Title %></title>


You cannot however handle the Meta tags in the same way. One solution to handle the Meta tags specified in the Content page is to use a custom Page class, which extends the System.Web.UI.Page class, wherein add support to handling the Description and Keywords as input in the @Page directive. This can be accomplished by adding appropriately overriding the OnLoadComplete event of the Page class, wherein the needed Meta tags are constructed using the values specified in the @Page directive and the same are added to the Page Header.

Check out this codepage link for a sample solution.