ASP.NET 2.0 中使用PreviousPage的强类型属性

PreviousPage:获取向当前页传输控件的页

1,不采用强类型方式访问

Page1页面:     

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>Untitled Page</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>        
        
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        
<br />
        
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/Page2.aspx" /></div>
    
</form>
</body>
</html>

Page2代码:     

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Page2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            TextBox txtName = (TextBox)PreviousPage.FindControl("txtName");
            Response.Write("Hello " + txtName.Text);
        }
    }
}

在接受Page1传过来的数据是,要先通过PreviousPage的FindControl找的控件在取值。

2,采用强类型方式访问

     在Page1的代码中添加一个property     

    public string strName
    {
        get { return this.txtName.Text; }        
    }

然后在Page2的页面中添加指令

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

这时,我们就可以在Page2的代码中使用PreviousPage的强类型属性了

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Page2 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (PreviousPage != null)
        {
            
//TextBox txtName = (TextBox)PreviousPage.FindControl("txtName");
            
//Response.Write("Hello " + txtName.Text);
            Response.Write(PreviousPage.strName);
        }
    }
}

作者:冰碟
出处:http://www.cnblogs.com/icebutterfly/
版权:本文版权归作者和博客园共有
转载:欢迎转载,为了保存作者的创作热情,请按要求【转载】,谢谢
要求:未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
原文地址:https://www.cnblogs.com/icebutterfly/p/1401711.html