Ordinary controls cannot be used in the head area of a web page, but it is sometimes very important, such as title, keywords, and description, which may be different on each page. So how can we dynamically set them according to the content?
Method 1: What asp can do, of course asp.net can do. As long as you write the entire page using Response.Write(), there is nothing that cannot be customized. Of course, you can also "<%=a certain member%" >". But obviously, this cannot take advantage of the characteristics of .net.
Method 2: Use the unique attribute of asp.net: runat="server", set an id for the title, and then make it a server variable, then you can set its text. But the html that comes out like this will also have an ID in it, which is really unpleasant to look at.
Method 3: Use Literal control, front desk: <HEAD>
<asp:Literal ID="lt_title" Runat="server" />
<asp:Literal ID="lt_keywords" Runat="server" />
<asp:Literal ID="lt_descri" Runat="server" />
</HEAD>Backend: private void Page_Load(object sender, System.EventArgs e)
{
lt_title.Text = "<title>Title</title>";
lt_keywords.Text = "<meta name="keywords" content="keywords">";
lt_descri.Text = "<meta name="description" content="description">";
}
This is basically perfect.
Furthermore, my page uses a lot of user controls, and these user controls have levels. The title of the page may be determined by a sub-user control in a user control, and the nesting level of user controls is not fixed. . So how to set it dynamically?
On the home page, make a base class of user control and add a public method to it:
public void SetTitle(string title)
{
SetLiteralText("lt_title", string.Format("<title>{0}</title>", title));
}Add another 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 inherit from this base class, and then call base.SetTitle("title") when you want to set the title of the page, and the task is simply completed. For other tags in the head area, the principle is the same as setting the title.