Asp.Net 在第二頁面上顯示結果案例

 

說明:

要求將TextBox中輸入的值在另一個頁面的Label中顯示。

頁面Default上控件

控件

名稱

Label

lblValue

TextBox

txtValue

Button

buttonSubmit


頁面ResultPage上控件

控件

名稱

Label

lblResult



方法一:

1.1在頁面ResultPagePage_load方法中加下邊代碼:


 protected void Page_Load(object sender, EventArgs e)
    {
        
try
        {
            
string sResult = ((TextBox)PreviousPage.FindControl("txtValue")).Text;
            labelResult.Text 
= sResult;           
        }
        
catch (Exception ex)
        {
            
throw ex;
        }
    }

1.2Default.aspx頁面的buttonSubmit按鈕上的PostbackUrl屬性設置為ResultPage頁面。

1.3現在運行,就可以看到結果了。

1.4說明:

1.4.1PreviousPage 的属性:

ASP.NET 网页中的跨页发送時,默认情况下,在 ASP.NET 网页中引起回发的按钮和其他控件将页提交回该页本身。在某些情况下,可能需要将一个页发送到其他页。page 类公开一个名为 PreviousPage 的属性。如果源页和目标页位于同一 ASP.NET 应用程序中,则目标页中的 PreviousPage属性包含对源页的引用。

1.4.2Button控件有一個新屬性PostbackUrl。此属性获取或设置单击Button 控件时从当前页发送到的网页的 URL

1.4.3PostbackUrl屬性設置完后的值為“~/ResultPage.aspx”,“~/表示同一層目錄中。

1.4.4Page.FindControl 方法


方法二:(創建強類型化的PreviousPage)

2.1Solution Exploer中選擇我們Web方案,再選擇Website|Add Folder|App_Code Folder,創建App_Code文件夾。

2.2在App_Code文件夾中使用Website|Add New item|Class增加一個名為RegistrationInformation.cs的C#文件。增加以下代碼:


 private string sValue;
    
public string Value
    {
        
get { return sValue; }
        
set { sValue = value; }
    }

2.3在Defalult.aspx.cs中添加公共屬性RegistrationInforamtion:


/// <summary>
    
/// 定義RegistrationInformation類型的,只讀屬性
    
/// </summary>
    public RegistrationInformation RegistrationInformation
    {
        
get
        {
            RegistrationInformation ri 
= new RegistrationInformation();
            ri.Value 
= txtValue.Text;
            
return ri;
        }
    }

2.4Default.aspx頁面的buttonSubmit按鈕上的PostbackUrl屬性設置為ResultPage頁面。

2.5在Result.aspx文件的Page指令下面PreviousPageType指令


<%@ PreviousPageType VirtualPath="~/Default.aspx" %>

2.6 ResultPage_aspx類的Page_load()中代碼如下:


        try
        {
            RegistrationInformation ri 
= PreviousPage.RegistrationInformation;
            ri.Value;
        }
        
catch (Exception ex)
        {

            
throw ex;
        }

2.7 編寫完成,可以查看結果。

2.8 說明:

2.8.1 我們在Result.aspx文件的Page指令下面加入“<%@ PreviousPageType VirtualPath="~/Default.aspx" %>”的PreviousPageType指令方可以Load事件中使用中“PreviousPage.RegistrationInformation;

2.8.2 PreviousPageType

@ PreviousPageType提供一种方法来获得上一页的强类型,可通过 PreviousPage 属性访问上一页。其属性有:TypeNameVirtualPath

TypeName:指定上一页的类型名称。

VirtualPath指定生成强类型的文件的路径。





原文地址:https://www.cnblogs.com/scottckt/p/1125457.html