頁與頁 (Page to Page) 的資料傳送

ASP的朋友都應該知道,Post 是經常用來將資料傳給另一頁ASP的方法,但是由於ASP.NET經常只會用到PostBack,那麼ASP.NET怎樣可以將資料傳到另一頁aspx呢?大家一齊來看看這個使用Property及Server.Transfer的方法吧!

1. 新增一個ASP.NET Web Application Project(專案),新增index
2. 在 WebForm 裡新增一個 TextBox,ID為tbName
3. 在 WebForm 裡新增一個 Button,ID為btnSubmit (如下圖)
4. 填入以下程式碼

Public Class MyWebForm
      Inherits System.Web.UI.Page

'設定一個名稱為Name及唯讀的property
Public ReadOnly Property Name() As String Get Return tbName.Text End Get End Property
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

'程式將轉到anotherPage.aspx繼續執行
Server.Transfer("anotherPage.aspx")
End Sub
End Class

5. 新增及開啟 anotherPage.aspx Web Form
6. 在 Page_Load 內填入以下程式碼

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) 
      Handles MyBase.Load

    '別忘記之前Web Form的Class是MyWebForm
   Dim pageSource As MyWebForm
   '就是Context.Handler取回之前Web Form的reference
   pageSource = CType(Context.Handler, MyWebForm)
   '取得Name property並顯示結果
Response.Write("Welcome " & pageSource.Name)

End Sub

執行結果



按 Submit 將顯示 "Welcome Vien"

text by eddiezone.net