方法1:asp能做到的,asp.net当然可以做到,只要你把整个页面都用Response.Write()写出来,没有什么不能自定义的,当然也可以"<%=某个成员%>"。但很明显,这样发挥不了.net的特点。
方法2:利用asp.net的特有属性:runat="server",给title设置一个id,然后让它成为服务器变量,那就可以设置其文本了。但这样出来的html里边也会带有id,看着实在不爽。
方法3:利用Literal控件,前台:
<
HEAD
>
< asp:Literal ID ="lt_title" Runat ="server" />
< asp:Literal ID ="lt_keywords" Runat ="server" />
< asp:Literal ID ="lt_descri" Runat ="server" />
</ HEAD >
后台:
< asp:Literal ID ="lt_title" Runat ="server" />
< asp:Literal ID ="lt_keywords" Runat ="server" />
< asp:Literal ID ="lt_descri" Runat ="server" />
</ HEAD >
private
void
Page_Load(
object
sender, System.EventArgs e)
{
lt_title.Text = " <title>标题</title> " ;
lt_keywords.Text = " <meta name=\ " keywords\ " content=\ " 关键字\ " > " ;
lt_descri.Text = " <meta name=\ " description\ " content=\ " 描述\ " > " ;
}
{
lt_title.Text = " <title>标题</title> " ;
lt_keywords.Text = " <meta name=\ " keywords\ " content=\ " 关键字\ " > " ;
lt_descri.Text = " <meta name=\ " description\ " content=\ " 描述\ " > " ;
}
这样就基本达到完美了。
更进一步,我的页面用了不少用户控件,并且这些用户控件有层次,而决定页面title的,可能是某个用户控件中的子用户控件来决定的,而且用户控件的嵌套层次不固定。 那要怎么来动态设置呢?
首页,做一个用户控件的基类,并且给它增加1个public方法:
public
void
SetTitle(
string
title)
{
SetLiteralText( " lt_title " , string .Format( " <title>{0}</title> " , title));
}
再增加一个private方法:
{
SetLiteralText( " lt_title " , string .Format( " <title>{0}</title> " , title));
}
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;
}
}
{
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;
}
}
这样,你的用户控件只需要让它继承自这个基类,然后在你想设置页面的title时调用base.SetTitle("标题"),就简单的完成了任务。对于head区其它标记,原理和设置title一样。