当用户在我的神州商城的产品分类导航中点击一个分类,会进入此分类的产品列表页面,我希望当前的类别名动态的显示在页面的Title上,有2种办法可以动态设置ASPX页面的Title值,第一种如下:
在aspx.cs文件中写一个SetTitle() 方法,根据URL中的CategoryID值去数据表中取当前的类别名,赋值给页面的title。

using System;
using System.Web;
using System.Web.UI;
using StoreDataSetTableAdapters;
public partial class ProductsByCategory : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetTitle(); //页面加载过程中设置Title值
}
}
protected void SetTitle() //设置页面的Title值,否则继承自模板页的Title值
{
var adapter = new QueriesTableAdapter();
string categoryname =Convert.ToString(adapter.GetCategoryNameByCategoryID(int.Parse(Context.Request["CategoryID"])));
this.Title = "神州商城 - "+categoryname+"类别";
}
}
但是我更推荐第二种:
第二种方法是先写一个继承了System.Web.UI.Page 的基类PageBase,在基类PageBase中定义一个PageTitle属性, 重写OnLoad方法让Title=PageTitle的值.
为什么不在分类的产品列表页面的cs中直接override重写Page的Title方法呢?以为很遗憾的是Page的Title方法不是virtual的,呵呵。

PageBase.cs代码:

PageBase.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for PageBase
/// </summary>
public class PageBase:System.Web.UI.Page
{
public PageBase()
{
//
// TODO: Add constructor logic here
//
}
protected virtual string PageTitle
{
get
{
return this.Title; //这里的get和set不重要,在基类中会重写它的get,set让PageTitle等于指定的值
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Title = this.PageTitle;
}
}
ASPX.CS中重写PageTitle

PageBase.cs protected override string PageTitle
{
get
{
string title = "神州商城 - {0}类别";
string categoryname = Convert.ToString(new QueriesTableAdapter().GetCategoryNameByCategoryID(int.Parse(Context.Request["CategoryID"])));
return string.Format(title,categoryname);
}
}