Tuesday, November 18, 2008

How to access HEAD tag from content page in asp.net

Sometimes we need to access head tag of master page from it content page for adding element tags like style, base ect. from its content page.
There could be various ways to add head tag elements from content page. Here I have mentioned how to add meta,style and base tag in the header section.

1. Adding META tags are quite easy.Add following C# code in the page load method of the content page.

HtmlMeta metatag = new HtmlMeta();
metatag.Name = "keywords";
metatag.Content = "ajax";
this.Header.Controls.Add(metatag);

2. Adding Style tag

HtmlGenericControl styles = new HtmlGenericControl("style");
styles.Attributes.Add("type", "text/css");
styles.InnerText = "a { color: #003399; text-decoration: none;}";
this.Header.Controls.Add(styles);

it will be rendered like this:-

< style type="text/css" > a {color: #003399;text-decoration: none;} < /style >

OR if you have already added style tag in it, you can access in like a variable and update it.

like:- < style type=”text/css” runat=”server” id=”myStyles” >

then in the content page it can be accessed like -

myStyles.InnerText += "a {color: #003399;text-decoration: none;}";

3. Adding Base tag - Add following C# code in the page load method of the content page.

HtmlGenericControl Tag = new HtmlGenericControl("BASE");
Tag.Attributes.Add("target", "_self");
this.Header.Controls.Add(Tag);
-----------------------------------
Another inovative way to access and update headed section is just add asp ContentPlaceHolder control in the Head section of your master page and then it can be access just like other ContentPlaceHolders with placing content tag in your content page for adding elements in the Header of the page.

like in the Master page(PopUp.master):-

< head runat="server" >

< title >< /title >

< asp:ContentPlaceHolder runat="server" id="MyHeader" >

< /asp:ContentPlaceHolder >

< /head >

In the content page-

< %@ Page Language="C#" MasterPageFile="~/Popup.master" AutoEventWireup="true" CodeFile="popUploadFile.aspx.cs"
Inherits="PopUp_popUploadFile" Title="Attachments" % >


< asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MyHeader" >

< style type="text/css" > a {color: #003399;text-decoration: none;} < /style >

< /style >

< /asp:Content >

No comments: