在老外的站上看到解決的好方法,故簡單編譯之:
在一個(gè)asp.net 的應(yīng)用中,經(jīng)常要?jiǎng)討B(tài)修改頁面的標(biāo)題,一個(gè)典型的例子就是,在一個(gè)頁面導(dǎo)航的控件中,希望用戶點(diǎn)選哪一個(gè)連接,在頁面的title里就顯示相關(guān)的內(nèi)容,舉個(gè)例子,比如一個(gè)網(wǎng)站,有如下的網(wǎng)站架構(gòu):
有圖書分類,下面再有中國圖書,外國圖書分類,則一般可以用樹形或者asp.net 2.0的新增加的導(dǎo)航欄控件
(sitemap),來實(shí)現(xiàn),比如
圖書--->中國圖書;
圖書---->外國圖書
等,而如果這個(gè)時(shí)候,能在頁面的<title>部分,也能顯示比如"圖書-->中國圖書"這樣,那就更加直觀明顯了,
在asp.net 2.0中,我們可以使用<head>部分的服務(wù)端控件來實(shí)現(xiàn)了,首先,要添加標(biāo)記
<head runat="server">
然后可以在page_load事件中,以如下形式改邊其title的內(nèi)容了,如
page.header.title = "the current time is: " & datetime.now.tostring()
,也可以簡單寫成page.title.
然后,我們可以通過這樣的辦法,將其于sitemap控件結(jié)合了,實(shí)現(xiàn)方法如下:
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
在上面的代碼中,首先預(yù)定義了兩個(gè)常量,然后逐步建立sitemap的結(jié)點(diǎn),一開始結(jié)點(diǎn)是null的,然后再調(diào)用
getpagetitlebasedonsitenavigation() 這個(gè)過程,在每建立一個(gè)sitemap的結(jié)點(diǎn)時(shí),用字符串進(jìn)行連接,最后返回給page.title即可實(shí)現(xiàn),當(dāng)然也可以用遞歸實(shí)現(xiàn)
新聞熱點(diǎn)
疑難解答
圖片精選