The head area of a webpage cannot use common controls, but it is sometimes important, such as title, keywords, and description. Each page may be different. How can we set them dynamically based on the content?
Method 1: What ASP can do, Asp.net can do, of course, as long as you use response for the entire page. write (). Nothing cannot be customized. Of course, it can also be "<% = A member %> ". However, it is obvious that the. NET feature cannot be used.
Method 2: Use the special attribute runat = "server" of Asp.net to set an ID for the title and make it a server variable. Then you can set its text. However, the HTML contains an ID, which is really unpleasant.
Method 3: Use the literal control, foreground:
< Head >
< ASP: literal ID = "Lt_title" Runat = "Server" />
< ASP: literal ID = "Lt_keywords" Runat = "Server" />
< ASP: literal ID = "Lt_descri" Runat = "Server" />
</ Head >
Background:
Private Void Page_load ( Object Sender, system. eventargs E)
{
Lt_title.text = " <Title> title </title> " ;
Lt_keywords.text = " <Meta name = \ " Keywords \ " Content = \ " Keyword \ " > " ;
Lt_descri.text = " <Meta name = \ " Description \ " Content = \ " Description \ " > " ;
}
In this way, it is almost perfect.
Furthermore, many user controls are used on my pages, and these user controls are hierarchical, which may be determined by the sub-user controls in a user control, the hierarchy of user controls is not fixed. How can we set it dynamically?
The home page is used as a base class of the user control and a public method is added to it:
Public Void Settitle ( String Title)
{
Setliteraltext ( " Lt_title " , String . Format ( " <Title> {0} </title> " , Title ));
}
Add a private method: Private Void Setliteraltext ( String ID, String Text)
{
Literal lt = Null ;
Control CTRL = This ;
Do
{
CTRL = CTRL. parent;
} While (CTRL ! = Null && CTRL. GetType (). fullname ! = " System. Web. UI. htmlcontrols. htmlform " );
If (CTRL ! = Null )
{
Lt = CTRL. findcontrol (ID) As Literal;
If (LT ! = Null )
Lt. Text = Text;
}
}
In this way, your user control only needs to let it inherit from this base class, and then calls base when you want to set the page title. settitle ("title. For other headers, the principle is the same as setting the title.