ASP.NET Tutorial/Page Lifecycle/Page Class

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

aspx page inherits from a "Page" class (C#)

   <source lang="csharp">

<%@ Page Inherits="ParentPage" src="Default.aspx.cs" %> <html><body>

  <form runat="server">
     <asp:Label id="lblMessage" runat="server" />
  
     <asp:DataGrid id="DataGrid1" 
                   runat="server" 
                   BorderColor="black" 
                   GridLines="Vertical" 
                   cellpadding="4" 
                   cellspacing="0" 
                   width="100%" 
                   Font-Name="Arial" 
                   Font-Size="8pt" 
                   HeaderStyle-BackColor="#cccc99"
                   ItemStyle-BackColor="#ffffff"
                   AlternatingItemStyle-Backcolor="#cccccc"
                   AutoGenerateColumns="True" />
     </asp:DataGrid>
  </form>

</body></html> File: Default.aspx.cs using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb; public class ParentPage : Page {

  public Label lblMessage;
  public DataGrid DataGrid1;
  
  private OleDbConnection objConn;
  
  void Page_Load(Object Sender, EventArgs e) {
     objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("EmployeeDatabase.mdb"));
     if (!Page.IsPostBack) {
        FillDataGrid();
     }
  }
  private void FillDataGrid() {
     FillDataGrid(-1);   
  }
  private void FillDataGrid(int EditIndex) {
     OleDbCommand objCmd = new OleDbCommand("select * from employee", objConn);
     OleDbDataReader objReader;
      
     try {
        objCmd.Connection.Open();
        objReader = objCmd.ExecuteReader();
        DataGrid1.DataSource = objReader;
        DataGrid1.DataBind();
        objReader.Close();
     } catch (OleDbException ex) {
        lblMessage.Text = "Error retrieving from the database.";
     }
      
     objCmd.Connection.Close();
  }
   

}</source>


aspx page inherits from a "Page" class (vb.net)

   <source lang="csharp">

<%@ Page Inherits="ParentPage" src="Default.aspx.vb" %> <html><body>

  <form runat="server">
     <asp:Label id="lblMessage" runat="server" />
  
     <asp:DataGrid id="DataGrid1" 
                   runat="server" 
                   AutoGenerateColumns="True" />
     </asp:DataGrid>
  </form>

</body></html>

File: Default.aspx.vb

Imports System Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Data Imports System.Data.OleDb Public Class ParentPage : Inherits Page

  public lblMessage as Label
  public DataGrid1 as DataGrid
  
  private strConnString as string = "Provider=" & _
     "Microsoft.Jet.OLEDB.4.0;" & _
     "Data Source=yourDatabase.mdb"
  private objConn as new OleDbConnection(strConnString)
  
  sub Page_Load(Sender as Object, e as EventArgs) 
     if Not Page.IsPostBack then
        FillDataGrid()
     end if
  end sub
  private sub FillDataGrid(Optional EditIndex as integer=-1)
     dim objCmd as OleDbCommand = new OleDbCommand("select * from tblUsers", objConn)
     dim objReader as OleDbDataReader
      
     try
        objCmd.Connection.Open()
        objReader = objCmd.ExecuteReader
     catch ex as OleDbException
        lblMessage.Text = "Error retrieving from the database."
     end try
      
     DataGrid1.DataSource = objReader
     DataGrid1.DataBind()
      
     objReader.Close
     objCmd.Connection.Close()
  end sub
   

End Class</source>


Expose the control through a page property

   <source lang="csharp">

<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">

   public string SearchString
   {
       get { return txtSearch.Text; }
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Button Search Typed</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblSearch"
       Text="Search:"
       Runat="server" />
   <asp:TextBox
       id="txtSearch"
       Runat="server" />
   <asp:Button
       id="btnSearch"
       Text="Go!"
       PostBackUrl="NextPage.aspx"
       Runat="server" />
   </form>

</body> </html>

File: NextPage.aspx

<%@ Page Language="C#" %> <%@ PreviousPageType VirtualPath="~/Default.aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">

   void Page_Load()
   {
       if (Page.PreviousPage != null)
       {
           lblSearch.Text = String.Format("Search For: {0}", PreviousPage.SearchString);
       }
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Button Search Results Typed</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblSearch"
       Runat="server" />
   </form>

</body> </html></source>


Fundamental properties in The Page Class

   <source lang="csharp">

Every web page is a custom class that inherits from System.Web.UI.Page. Property Description IsPostBack Boolean property

                 indicates whether this is the first time the page is being run(false) or 
                 whether the page is being resubmitted in response to a control event. 
                 

EnableViewState When set to false, this overrides the EnableViewState property of the

                 contained controls, thereby ensuring that no controls will maintain state information.

Application This collection holds information that"s shared between all users in your website.

                 You can use the Application collection to count the number of times a page has been visited. 

Session This collection holds information for a single user.

                 Uou can use it to store the items in the current user"s shopping basket on an e-commerce website. 

Cache This collection stores objects that are time-consuming to create

Request This refers to an HttpRequest object.

                 You can use the HttpRequest object to get information about the user"s browser
                 

Response This refers to an HttpResponse object Server This refers to an HttpServerUtility object User If the user has been authenticated, this property will be initialized with user information.</source>


Is page valid

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>IsValid property example</title>
     <script runat="server">
        Sub Page_Load()
           If IsPostBack Then
              Page.Validate()
              If Page.IsValid Then
                 myMessage.Text = "Page is valid."
              Else
                 myMessage.Text = "Page is not valid."
              End If
           End If
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     Enter your name:
     <asp:textbox id="name" runat="server"/>
     <asp:requiredfieldvalidator 
        id="rfvName"
        controltovalidate="name"
        enableclientscript="false"
        errormessage="Required!"
        runat="server"/>
     
<asp:button id="submit" Text="Submit" runat="server"/>
<asp:label id="myMessage" runat="server"/> </form>

</body> </html></source>


Page.ErrorPage

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>ErrorPage property example</title>
     <script runat="server">
        Sub Page_Load()
           Page.ErrorPage = "NextPage.aspx"
           Dim x, y, overflow As Integer
           x = 1
           y = 0
           overflow = x/y
           "This code will not be executed
           Message.Text = "Error Page is " & Page.ErrorPage & "."
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html> File: NextPage.aspx


<%@ Page Language="vb" %> <html>

  <head>
     <title>ErrorPage property example</title>
     <script runat="server">
        Sub Page_Load()
           Message.Text = "An error occurred. Please try again later."
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html></source>


Page.HasControls

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>HasControls method example</title>
     <script runat="server">
        Sub Page_Load()
           If Page.HasControls = True Then
              Message.Text = "The page contains controls."
           Else
              Message.Text = "The page does not contain controls."
           End If 
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html></source>


Page.ResolveUrl

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>ResolveUrl method example</title>
     <script runat="server">
        Sub Page_Load()
           Message.Text = Page.ResolveUrl("Default.aspx")
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html></source>