asp.net 2.0中動態修改頁面標題

asp.net 2.0中動態修改頁面標題
 
<script src="/adfile/stop.js" type="text/javascript"></script>
 在老外的站上看到解決的好方法,故簡單編譯之:
在一個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即可實現,當然也可以用遞歸實現

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章