当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET 2.0中动态修改页面标题

ASP.NET
asp.net图片加水印
Asp.Net中页面运行时动态载入的UserControl内元素的事
ASP.NET底层架构探索之再谈.NET运行时(二)
借助封装类实现线程调用带参方法
面向对象设计思想(C#)
asp.net URL重写(URLRewriter) 简化版
GUID在.net里的使用,就用System.Guid结构
不要忽略c#中的using和as操作符
C#中ref和out的使用小结
C#的Web XML编程
asp.net2.0下 如何实现服务器端压缩包自解压
javascript如何调用C#后台代码中的过程 和ASP.NET调用
在ASP.NET中自动给URL加上超链接
ASP.NET 中处理页面“回退”的方法
ASP.NET的四种错误机制
asp.net跳转页面的三种方法比较
ASP.NET2.0中将GridView导出到Excel文件中
ASP.NET 2.0中GridView无限层复杂表头的实现
ASP.NET 2.0 中动态添加 GridView 模板列
十天学会ASP.net之第一天

ASP.NET 2.0中动态修改页面标题


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 60 ::
收藏到网摘: n/a

在老外的站上看到解决的好方法,故简单编译之:

在一个asp.net 的应用中,经常要动态修改页面的标题,一个典型的例子就是,在一个页面导航的控件中,希望用户点选哪一个连接,在页面的title里就显示相关的内容,举个例子,比如一个网站,有如下的网站架构:

有图书分类,下面再有中国图书,外国图书分类,则一般可以用树形或者asp.net 2.0的新增加的导航栏控件(sitemap),来实现,比如

图书--->中国图书;图书---->外国图书等,而如果这个时候,能在页面的<title>部分,也能显示比如"图书-->中国图书"这样,那就更加直观明显了,在asp.net 2.0中,我们可以使用<head>部分的服务端控件来实现了,首先,要添加标记<head runat="server">

然后可以在page_load事件中,以如下形式改边其title的内容了,如

Page.Header.Title = "The current time is: " & DateTime.Now.ToString() ,也可以简单写成page.title

然后,我们可以通过这样的办法,将其于sitemap控件结合了,实现方法如下:

以下为引用的内容:

Const DEFAULT_UNNAMED_PAGE_TITLE As String = "Untitled Page"
    Const DEFAULT_PAGE_TITLE As String = "Welcome to my Website!!"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Set the page's title, if needed
        If String.IsNullOrEmpty(Page.Title) OrElse Page.Title = DEFAULT_UNNAMED_PAGE_TITLE Then
            If SiteMap.CurrentNode Is Nothing Then
                Page.Title = DEFAULT_PAGE_TITLE
            Else
                Page.Title = GetPageTitleBasedOnSiteNavigation()

                'Can also use the following if you'd rather
                'Page.Title = GetPageTitleBasedOnSiteNavigationUsingRecursion(SiteMap.CurrentNode)
            End If
        End If
    End Sub

    Private Function GetPageTitleBasedOnSiteNavigation() As String
        If SiteMap.CurrentNode Is Nothing Then
            Throw New ArgumentException("currentNode cannot be Nothing")
        End If

        'We are visiting a page defined in the site map - build up the page title
        'based on the site map node's place in the hierarchy

        Dim output As String = String.Empty
        Dim currentNode As SiteMapNode = SiteMap.CurrentNode

        While currentNode IsNot Nothing
            If output.Length > 0 Then
                output = currentNode.Title & " :: " & output
            Else
                output = currentNode.Title
            End If

            currentNode = currentNode.ParentNode
        End While

        Return output
    End Function

在上面的代码中,首先预定义了两个常量,然后逐步建立sitemap的结点,一开始结点是null的,然后再调用GetPageTitleBasedOnSiteNavigation() 这个过程,在每建立一个sitemap的结点时,用字符串进行连接,最后返回给page.title即可实现,当然也可以用递归实现。