ASP.NET四種頁面導(dǎo)航方式

2010-08-28 10:48:01來源:西部e網(wǎng)作者:

  在ASP.NET應(yīng)用中,Web表單之間的導(dǎo)航有多種方式:用超級鏈接,用Response.Redirect,用Server.Transfer,或者用Server.Execute。本文將分析這四種導(dǎo)航方式的異同及其優(yōu)缺點(diǎn),幫助你選擇最佳的導(dǎo)航方式。

  一、超級鏈接

  從一個表單進(jìn)入另一個表單最簡單的方式是使用HTML超級鏈接控件。在Web表單中,使用超級鏈接的HTML代碼類如:

<a href="WebForm2.aspx">WebForm2</a>

  當(dāng)用戶點(diǎn)擊該超級鏈接,WebForm2.aspx執(zhí)行并將結(jié)果發(fā)送到瀏覽器。超級鏈接導(dǎo)航方式幾乎可用于任何地方,包括HTML頁面和普通的ASP頁面。ASP.NET還提供了另一種可替換使用的方法,即HyperLink服務(wù)器控件:

<form id="Form1" method="post" runat="server">
<asp:HyperLink id="HyperLink1" runat="server"
NavigateUrl="WebForm2.aspx">WebForm2</asp:HyperLink>
</form>

  上述HTML代碼的運(yùn)行結(jié)果和第一個例子相同,因?yàn)锳SP.NET把HyperLink Web服務(wù)器控件視為一個HTML超級鏈接控件。但兩者有一點(diǎn)重要的區(qū)別,HyperLink Web服務(wù)器控件可以在服務(wù)器端編程。具體地說,可以在程序代碼中改變它的NavigateUrl屬性,從而允許構(gòu)造出具體目標(biāo)可根據(jù)應(yīng)用的當(dāng)前狀態(tài)動態(tài)變化的超級鏈接,例如:

Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
    HyperLink1.NavigateUrl = "WebForm3.aspx"
End Sub

  這段代碼執(zhí)行后,如果用戶點(diǎn)擊鏈接,他看到的將是WebForm3.aspx,而不是WebForm2.aspx。

  二、用程序控制重定向

  雖然超級鏈接能夠從一個頁面導(dǎo)航到另一個頁面,但這種導(dǎo)航方式是完全由用戶控制的。有些時候,我們可能要用代碼來控制整個導(dǎo)航過程,包括何時轉(zhuǎn)到另一個頁面。在這些場合,ASP.NET有三種不同的方式可以達(dá)到相似的目的:調(diào)用Response對象的Redirect方法,調(diào)用Server對象的Transfer或Execute方法。這三種導(dǎo)航方式的行為基本相似,但也有區(qū)別。

  2.1 Response.Redirect

  Response.Redirect方法導(dǎo)致瀏覽器鏈接到一個指定的URL。當(dāng)Response.Redirect()方法被調(diào)用時,它會創(chuàng)建一個應(yīng)答,應(yīng)答頭中指出了狀態(tài)代碼302(表示目標(biāo)已經(jīng)改變)以及新的目標(biāo)URL。瀏覽器從服務(wù)器收到該應(yīng)答,利用應(yīng)答頭中的信息發(fā)出一個對新URL的請求。

  這就是說,使用Response.Redirect方法時重定向操作發(fā)生在客戶端,總共涉及到兩次與服務(wù)器的通信(兩個來回):第一次是對原始頁面的請求,得到一個302應(yīng)答,第二次是請求302應(yīng)答中聲明的新頁面,得到重定向之后的頁面。

  2.2 Server.Transfer

  Server.Transfer方法把執(zhí)行流程從當(dāng)前的ASPX文件轉(zhuǎn)到同一服務(wù)器上的另一個ASPX頁面。調(diào)用Server.Transfer時,當(dāng)前的ASPX頁面終止執(zhí)行,執(zhí)行流程轉(zhuǎn)入另一個ASPX頁面,但新的ASPX頁面仍使用前一ASPX頁面創(chuàng)建的應(yīng)答流。

  如果用Server.Transfer方法實(shí)現(xiàn)頁面之間的導(dǎo)航,瀏覽器中的URL不會改變,因?yàn)橹囟ㄏ蛲耆诜⻊?wù)器端進(jìn)行,瀏覽器根本不知道服務(wù)器已經(jīng)執(zhí)行了一次頁面變換。

  默認(rèn)情況下,Server.Transfer方法不會把表單數(shù)據(jù)或查詢字符串從一個頁面?zhèn)鬟f到另一個頁面,但只要把該方法的第二個參數(shù)設(shè)置成True,就可以保留第一個頁面的表單數(shù)據(jù)和查詢字符串。

  同時,使用Server.Transfer時應(yīng)注意一點(diǎn):目標(biāo)頁面將使用原始頁面創(chuàng)建的應(yīng)答流,這導(dǎo)致ASP.NET的機(jī)器驗(yàn)證檢查(Machine Authentication Check,MAC)認(rèn)為新頁面的ViewState已被篡改。因此,如果要保留原始頁面的表單數(shù)據(jù)和查詢字符串集合,必須把目標(biāo)頁面Page指令的EnableViewStateMac屬性設(shè)置成False。

  2.3 Server.Execute

  Server.Execute方法允許當(dāng)前的ASPX頁面執(zhí)行一個同一Web服務(wù)器上的指定ASPX頁面,當(dāng)指定的ASPX頁面執(zhí)行完畢,控制流程重新返回原頁面發(fā)出Server.Execute調(diào)用的位置。

  這種頁面導(dǎo)航方式類似于針對ASPX頁面的一次函數(shù)調(diào)用,被調(diào)用的頁面能夠訪問發(fā)出調(diào)用頁面的表單數(shù)據(jù)和查詢字符串集合,所以要把被調(diào)用頁面Page指令的EnableViewStateMac屬性設(shè)置成False。

  默認(rèn)情況下,被調(diào)用頁面的輸出追加到當(dāng)前應(yīng)答流。但是,Server.Execute方法有一個重載的方法,允許通過一個TextWriter對象(或者它的子對象,例如StringWriter對象)獲取被調(diào)用頁面的輸出,而不是直接追加到輸出流,這樣,在原始頁面中可以方便地調(diào)整被調(diào)用頁面輸出結(jié)果的位置。

  為說明其工作過程,下面我們創(chuàng)建一個Web表單,放入一個按鈕控件(Button1)和一個文本控件(Literal1),在設(shè)計(jì)界面中轉(zhuǎn)入代碼視圖,加入一個System.IO名稱空間的Imports語句,然后加入用戶點(diǎn)擊按鈕時執(zhí)行的代碼:

Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
    Dim sw As StringWriter = New StringWriter()
    Server.Execute("WebForm2.aspx", sw)
    Literal1.Text = sw.ToString()
End Sub

  然后為同一個Web應(yīng)用創(chuàng)建第二個頁面WebForm2.aspx。轉(zhuǎn)入該頁面的HTML視圖,修改其Page指令禁止ViewState檢查:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm2.aspx.vb"
  Inherits="Navigate.WebForm2" EnableViewStateMac="false"%>

  再轉(zhuǎn)到設(shè)計(jì)視圖,為第二個頁面增加一些控件。接下來,把第一個頁面設(shè)置成默認(rèn)頁面,啟動應(yīng)用。點(diǎn)擊按鈕,WebForm2的控件將顯示在WebForm1中放置Literal按鈕的地方,如圖一,注意頁面標(biāo)題和URL仍舊顯示原始頁面WebForm1。

  \

圖一:用Server.Execute合并兩個源文件的頁面

  用Server.Transfer或Server.Execute方法實(shí)現(xiàn)導(dǎo)航時,還要注意一點(diǎn):最后得到的頁面可能不是合法的HTML頁面,因?yàn)樽罱K返回給客戶端的頁面可能包含多個<HTML>和<BODY>等標(biāo)記。IE瀏覽器看來能夠容忍并正確處理這類情形,但如果用戶要用到其他的瀏覽器,最好仔細(xì)測試一下。

  三、比較與選擇

  既然從一個頁面導(dǎo)航到另一個頁面的辦法有這么多,應(yīng)該如何選擇最佳的導(dǎo)航方式呢?下面是一些需要考慮的因素:

  ·如果要讓用戶來決定何時轉(zhuǎn)換頁面以及轉(zhuǎn)到哪一個頁面,超級鏈接最適合。
  ·如果要用程序來控制轉(zhuǎn)換的目標(biāo),但轉(zhuǎn)換的時機(jī)由用戶決定,使用Web服務(wù)器的HyperLink控件,動態(tài)設(shè)置其NavigateUrl屬性。
  ·如果要把用戶連接到另一臺服務(wù)器上的資源,使用Response.Redirect。
  ·用Response.Redirect把用戶連接到非ASPX的資源,例如HTML頁面。
  ·如果要將查詢字符串作為URL的一部分保留,使用Response.Redirect。
  ·如果要將執(zhí)行流程轉(zhuǎn)入同一Web服務(wù)器的另一個ASPX頁面,應(yīng)當(dāng)使用Server.Transfer而不是Response.Redirect,因?yàn)镾erver.Transfer能夠避免不必要的網(wǎng)絡(luò)通信,從而獲得更好的性能和瀏覽效果。
  ·如果要捕獲一個ASPX頁面的輸出結(jié)果,然后將結(jié)果插入另一個ASPX頁面的特定位置,則使用Server.Execute。
  ·如果要確保HTML輸出合法,請使用Response.Redirect,不要使用Server.Transfer或Server.Execute方法。


原文:

Managing ASP.NET Navigation

by Mike Gunderloy
04/08/2003

In an ASP.NET application, you can move between Web Forms in a variety of ways: with hyperlinks, with Response.Redirect, with Server.Transfer, or with Server.Execute. In this article, I will take a look at these various navigation methods and help you choose the appropriate one for your application.

Hyperlinks
The simplest possible way to navigate from one Web Form to another is with an HTML hyperlink control. On a Web Form, that might look like this:


<a href="WebForm2.aspx">WebForm2</a>
When the user clicks on the hyperlink, WebForm2.aspx is served up to their browser. You can use this technique just about anywhere, including on HTML pages and in classic ASP. ASP.NET gives you another alternative, the HyperLink Web Server control:

<form id="Form1" method="post" runat="server">
 <asp:HyperLink id="HyperLink1" runat="server"
 NavigateUrl="WebForm2.aspx">WebForm2</asp:HyperLink>
</form>
At runtime, this HTML has exactly the same effect as the first example, since ASP.NET renders the HyperLink Web Server control as an HTML hyperlink control. There is one key difference, though: the Web Server control can be programmed on the server side. In particular, you can change its NavigateUrl property in code, opening up the possibility of a hyperlink whose destination depends on some part of your application's state:

Private Sub Button1_Click( _
 ByVal sender As System.Object, _
 ByVal e As System.EventArgs) _
 Handles Button1.Click
    HyperLink1.NavigateUrl = "WebForm3.aspx"
End Sub
If the user clicks on the hyperlink after this code has executed, then the link will serve up WebForm3.aspx instead of WebForm2.aspx.

Controlling Transfers Yourself
Although hyperlinks do transfer your application from one page to another, they do so completely under the control of the user. Sometimes it's convenient to control the entire process in code yourself, including deciding when to move to another page. As it happens, ASP.NET provides three different methods to accomplish this. You can call the Redirect method of the Response object, or the Transfer or Execute methods of the Server object. Although they behave very similarly, there are differences between these three methods.

Response.Redirect
The Response.Redirect method causes the browser to connect to a specified URL. When the Response.Redirect() method is called, it creates a response whose header contains a 302 (Object Moved) status code and the target URL. When the browser receives this response from the server, it uses this header information to generate another HTTP request to the new URL. When using the Response.Redirect method, the redirection happens at the client side and involves two round trips to the server: one to request the original page, which is met by the 302 response, and then a second to request the redirected page.

Server.Transfer
The Server.Transfer method transfers execution from the current ASPX file to another ASPX file on the same web Server. When your code calls the Server.Transfer method, the current ASPX page terminates execution and the flow of control is transferred to another ASPX page. The new ASPX page still uses the response stream created by the prior ASPX page. When you use this method to navigate between pages, the URL in the browser still shows the original page, because the redirection occurs on the server side and the browser remains unaware of the transfer.

By default, the Server.Transfer method does not pass the form data or the query string of the original page request to the transferred page. But you can preserve the form data and query string of the original page by setting the optional second argument of the method to True. When you use this technique, though, you need to aware of one thing: the destination page uses the same response stream that was created by the original page, and therefore the hidden _VIEWSTATE field of the original page ends up on the second page. This causes the ASP.NET machine authentication check (MAC) to assume that the ViewState of the new page has been tampered with. Therefore, when you choose to preserve the form and query string collection of the original page, you must set the EnableViewStateMac attribute of the Page directive to False for the destination page.

Server.Execute
The Server.Execute method allows the current ASPX page to execute a specified ASPX page on the same web server. After the specified ASPX page is executed, the control transfers back to the original page from which the Server.Execute method was called. This technique of page navigation is analogous to making a function call to an ASPX page. The called ASPX page has access to the form and query string collections of the calling page, and thus you need to set the EnableViewStateMac attribute of the Page directive to False on the executed page.

By default, the output of the executed page is added to the current response stream. This method also has an overloaded version in which the output of the redirected page can be fetched in a TextWriter object (or one of its children, such as a StringWriter object) instead of added directly to the response stream. This helps you to control where to place the output in the original page.

To see how this works, create a Web Form in a test ASP.NET application and place a Button control (Button1) and a Literal control (Literal1) on the Web Form. Switch to code view and add an Imports statement for the System.IO namespace. Then add code to execute when the user clicks the button:

Private Sub Button1_Click( _
 ByVal sender As System.Object, _
 ByVal e As System.EventArgs) _
 Handles Button1.Click
    Dim sw As StringWriter = New StringWriter()
    Server.Execute("WebForm2.aspx", sw)
    Literal1.Text = sw.ToString()
End Sub
Now create a second Web Form in the same application, WebForm2.aspx. Switch to the HTML view of this second Web Form and modify its Page directive to disable ViewState checking:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm2.aspx.vb"
  Inherits="Navigate.WebForm2" EnableViewStateMac="false"%>

Switch back to design view and add some controls to the second Web Form. Now set the first Web Form as the default page and start the application. Click the button, and the controls from WebForm2 will be displayed in the area of WebForm1 where you placed the Literal control, as shown in Figure 1. You'll note from the URL and page title that the browser is still displaying WebForm1.


Figure 1: A page in the browser composed by using Server.Execute to combine two source files.
 

There's one more thing to be aware of when you use the Server.Transfer or Server.Execute methods to navigate: the ultimate page may not be valid HTML. That's because the response to the client will contain multiple <html> and <body> tags, among other tags. Internet Explorer seems to tolerate this situation just fine, but you may want to test the results carefully if your users prefer a different browser.

Decisions, Decisions
So, given these choices for navigating from page to page, how do you select the appropriate one for your application? Here are some things to think about:

·Hyperlinks are appropriate when you want the end user to control when navigation is performed, or to choose where to go.

·To control the user's destination, but let them decide when to get there, use a Web Server HyperLink control whose NavigateUrl property is dynamically set.

·Use Response.Redirect to connect to resources outside of the web server where your page is hosted.

·Use Response.Redirect to connect to non-ASPX resources such as HTML pages.

·Use Response.Redirect if you need to preserve a query string as an explicit part of the URL.

·When you want to transfer control to an ASPX page residing on the same web server, you should use Server.Transfer instead of Response.Redirect because Server.Transfer will avoid the unnecessary round trip and provide better performance and a better user experience.

·To capture the output from an ASPX page and display it at a specified location on another ASPX page, use Server.Execute.

·If valid HTML output is essential, use Response.Redirect instead of either the Server.Transfer or Server.Execute methods.

 

關(guān)鍵詞:ASP.NET

贊助商鏈接: