CSDN博客

img colayungnew

Page类

发表于2004/10/23 16:21:00  1770人阅读

分类: 学习笔记


    
 Protected ReadOnly Property HelperID() As String
         Get
            Return "__" & ClientID & "_State"
         End Get
      End Property
     
      Protected Overrides Sub OnInit(e As EventArgs)
         MyBase.OnInit(e)
 
         If Not (Page Is Nothing) Then
            Page.RegisterRequiresPostBack(Me)
         End If
      End Sub
     
      Protected Overrides Sub OnPreRender(e As EventArgs)
         MyBase.OnPreRender(e)
        
         If Not (Page Is Nothing) Then
            Page.RegisterHiddenField(HelperID, Selected.ToString())
         End If
      End Sub
     
      Protected Overrides Sub Render(writer As HtmlTextWriter)
         Dim postback As String = ""
         If Not (Page Is Nothing) Then
            postback = Page.GetPostBackEventReference(Me) & ";"
         End If
        
         Dim click As String = "onclick=""var sel=getAttribute('selected'); sel = (sel.toLowerCase() == 'true'); sel=!sel;

setAttribute('selected', sel.toString());this.style.backgroundColor=sel?'red':'white';" & HelperID & ".value=sel.toString();" & postback &

""""
         Dim style As String = "style=""cursor:hand;background-color:" & IIf(Selected, "red", "white").ToString() & """"
         Dim selectedPiece As String = "selected=""" & Selected.ToString() & """"
         writer.Write(("<span " & style & " " & click & " " & selectedPiece & ">" & Text & "</span>"))
      End Sub
     
      Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean Implements

IPostBackDataHandler.LoadPostData
         Dim value As String = postCollection(HelperID)
        
         If Not (value Is Nothing) Then
            Dim newValue As Boolean = String.Compare(value, "true", True) = 0
            Dim oldValue As Boolean = Selected
           
            Selected = newValue
           
            ' If there is a change, raise a change event.
            Return newValue <> oldValue
         End If
        
         Return False
      End Function
     
      Sub RaisePostDataChangedEvent() Implements IPostBackDataHandler.RaisePostDataChangedEvent
         ' There was a change, so raise any events.
         RaiseEvent SelectedChanged(Me, EventArgs.Empty)
      End Sub

      对症下药,查阅了Page类的相关资料
      Page类与扩展名为.aspx的文件相关联,这些文件在运行时被编译为page对象,缓存在服务器内存中
      page对象充当页中所有服务器控件(实现INamingcontainer接口的控口或实现该接口的控件的子级除外)的命名容器.
      page类的签名如下:
 
      public class page
        inherits templatecontrol
        implements IHttpHandler
        ......

      TemplateControl类为Page类和userControl类提供一组基本功能,其签名如下:
      mustinherit public class templateControl
        inherits control
        implements INamingContainer
        ......

      Page类属性:

      ClientID(从Control继承)  由asp.net生成的服务器控件标识符
                               不论是否指定服务器控件的id属性,asp.net自动为服务器控件生成ClientID,用于识别客户端操作的控件.     
                               任何使用ID属性分配给服务器控件的名称都重写此属性值
                               public overridable readonly proerty clientid as string

      ID                       Page类的特定实例的标识符
                               overrides public property ID as string

      NamingContainer          获取对服务器控件的命名容器铁引用,以区分具有相同Control.ID属性值的服务器控件
                               public overridable readonly property Namingcontainer as control
     
      UniqueID                 获取服务器控件的唯一的,以分层形式限定的标识符
                               与ID不同,该属性包含服务器控件命名容器的标符,处理页请求时自动生成此标识符
                               此属性用于区分嵌套的控件时尤其重要
                在页面上的表现形式为myRepeater:ct10:mylabel   myRepeater:ctl1:mylabel等
                               Public Overridable ReadOnly Property UniqueID as string

   User                     有关发出请求的用户的信息
                               该属性使用HttpContext对象的User属性获得正在请求页的用户有关身份验证信息
                public ReadOnly Property User as IPrincipal

     Validators               页上包含的全部验证控件的集合
                               调用page.validate方法将导致对该集合所含的各验证服务控件执行验证逻辑运算,然后设置page.isvalid属性      

                Public ReadOnly Property Validators as ValidatorCollect
 
   方法:
    GetPostBAckClientEvent         获取对客户端脚本函数的引用,该函数在被调用时将导致服务嚣回发到窗口
                            Public Function GetPostBackClientEvent(byval Control as control,argument as string) as string
                                     'control:接收客户端事件回发的服务器控件
                     'Argument:传递到IPostBackEventHandler.RaisePostBackEvent方法的string参数 
                     'return:客户端事件的String

      GetostBackClientHyperLink      将javascript追加到GetPostBackEventReference调用的返回的开头,从而使服务器可以进行超链接的回发处理
                                    Public Function GetPostBackClientHyperlink(control As Control,argument As String ) As String      

                                     'control:处理回发的服务器控件。
                                     'argument:传递给服务器控件的参数。
                                     'return:客户端函数的名称和处理传递给控件的函数和参数的服务器控件的 ID 属性。


      GetPostBackEventReference      获取对客户端脚本函数的引用,调用该函数将使服务器发送回该页
                   Overloads Public function GetPostBackEventReference(control as control) as string
                                     'Control:要在服务器上处理回发的服务器控件。
                   'Return:可插入客户端事件处理程序的客户端函数调用的文本

                                     overloads public function GetPostBackEventReference(Control as control ,argument as string) as string
                                     'control:要处理回发的服务器控件。
                                     'argument:传递给服务器控件的参数。
                                     'Return:可插入客户端事件处理程序的客户端函数调用的文本。

                     Protected Overrides Sub Render(writer As HtmlTextWriter)
                         writer.Write(("<a href=""javascript:" + Page.GetPostBackEventReference(Me, "inc") + """>Increase

                                       Number</a>"))
                         writer.Write(" or ")
                         writer.Write(("<a href=""javascript:" + Page.GetPostBackEventReference(Me, "dec") + """>Decrease

                                        Number</a>"))
                     End Sub 'Render


      IsClientScriptBlockRegistered   确定该页是否注册了客户端脚本块
                   public function isClientScriptBlockRegistered(key as string) as boolean
                                      'key:要搜索的客户端脚本的字符串关键字
                   'return:true/false

               Sub Page_Load( sender as Object,e as EventArgs)
                   Dim scriptString as String = "<script language=JavaScript> function DoClick() {"
                   scriptString += "myForm.show.value='Welcome to Microsoft .NET'}<"
                   scriptString += "/"
                   If(Not IsClientScriptBlockRegistered("clientScript"))   RegisterClientScriptBlock("clientScript", scriptString)
                End Sub

   IsStartupScriptRegistered   确定Page对象是否注册了客户端启动脚本

                public Sub Page_Load(Sender As Object,e As EventArgs)    
                      ' Form the script to be registered at client side.
                        Dim scriptString As String  = "<script language=JavaScript> function DoClick() {"
                        scriptString += "showMessage2.innerHTML='<h4>Welcome to Microsoft .NET!</h4>'}"
                        scriptString += "function Page_Load(){ showMessage1.innerHTML="
                        scriptString += "'<h4>RegisterStartupScript Example</h4>'}<"
                        scriptString += "/"
                        scriptString += "script>"
                            If(Not Me.IsStartupScriptRegistered("Startup")) Then
                       Me.RegisterStartupScript("Startup", scriptString)
                            End If
                   End Sub

   LoadControl                    从TemplateControl继承的方法,从用户控件文件获取UserControl对象
                   
                   Sub  Page_Load(Sender As Object, e As EventArgs)
                     Dim myControl1 As MyControl = CType(LoadControl("TempControl_Samples1.vb.ascx"),MyControl)
                     Controls.Add(myControl1)
                   end sub

      LoadTemplate                    从外部文件获取ITemplate接口的实例,继承自TemplateControl
                                    
                                      Sub Page_Load(sender As [Object], e As EventArgs)
                                         If Not IsPostBack Then
                                            DataList1.AlternatingItemTemplate = LoadTemplate("newtemplate.ascx")
                                            DataList1.DataSource = CreateDataSource()
                                            DataList1.DataBind()
                                         End If
                                      End Sub 'Page_Load

     ParseControl                     将输入字符串分析为WEB窗体页或用户控件的control

                                      Sub Page_Load(sender As Object, e As System.EventArgs)
                                         Dim c As Control
                                         c = ParseControl("<asp:button text='Click here!' runat='server' />")
                                         myPlaceholder.Controls.Add(c)
                                      End Sub 'Page_Load

     RegisterArrayDeclaration         声明一个值,该值在页呈现时声明为ecmaScript数组声明
                   基于脚本的控件可以使用该方法在数组内部声明它们自身,以便客户端脚本库可以与同一类型的所有控件一起工作

                                       Dim scriptString As String = "<script language=JavaScript> function doClick() {"
                                       scriptString += "for(var index=0;index < myArray.length;index++)"
                                       scriptString += " myArray[index].show(); } <"
                                       scriptString += "/" + "script>"
                                       RegisterStartupScript("arrayScript", scriptString)
                                       RegisterArrayDeclaration("myArray", "new obj('x'),new obj('y'),new obj('z')")

     RegisterClientScriptBlock        允许asp.net服务器控件在page中发出客户端脚本块
                   客户端脚本在page对象的<form runat=server>元素的开始标记后发出
                   脚本块是在呈现输出的对象被定义时发出的,因此必须同时包括<script>元素的两个标记
                   通过使用关键字标识脚本,多个服务器控件实例可以请求该脚本块,而不用将其发送输出流两次。

                                      Sub Page_Load( sender as Object,e as EventArgs)
                                          Dim scriptString as String = "<script language=JavaScript> function DoClick() {"
                                          scriptString += "myForm.show.value='Welcome to Microsoft .NET'}<"
                                          scriptString += "/"                                      
                                          scriptString += "script>"
                                          If(Not IsClientScriptBlockRegistered("clientScript"))
                                              RegisterClientScriptBlock("clientScript", scriptString)
                                          End If
                                      End Sub
    
     RegisterHiddenField              使服务器控件能够在窗体上自动注册隐藏字段,呈现htmlform服务器控件时,将该字段发送到page

                                      Dim scriptString As String = "<script language=JavaScript> function doClick() {"
                                      scriptString += "document.write('<h4>' + myForm.myHiddenField.value+ '</h4>');}<"
                                      scriptString += "/" + "script>"  
                                      RegisterHiddenField("myHiddenField", "Welcome to Microsoft .NET!")
                                      RegisterOnSubmitStatement("submit", "document.write('<h4>Submit button clicked.</h4>')")
                                      RegisterStartupScript("startup", scriptString)

     RegisterRequiresPostBack         将控件注册为需要回发处理的控件
                   
                                      Sub Text_Change(sender As Object, e As EventArgs)
                                         myLabel.Text = "<b>Welcome " + myTextBox.Text + " to ASP.NET</b>"
                                      End Sub 'Text_Change
                                      Sub Page_Load(sender As Object, e As EventArgs)
                                         If Not IsPostBack Then
                                            Me.RegisterRequiresPostBack(myTextBox)
                                         End If
                                      End Sub 'Page_Load

     RegisterOnSubmitStatement        使页面能够访问客户端onSubmit事件。脚本应该是注册在其他地方的对客户端代码的函数调用。

                                      Dim scriptString As String = "<script language=JavaScript> function doClick() {"
                                      scriptString += "document.write('<h4>' + myForm.myHiddenField.value+ '</h4>');}<"
                                      scriptString += "/" + "script>"  
                                      RegisterHiddenField("myHiddenField", "Welcome to Microsoft .NET!")
                                      RegisterOnSubmitStatement("submit", "document.write('<h4>Submit button clicked.</h4>')")
                                      RegisterStartupScript("startup", scriptString)

     RegisterRequiresRaiseEvent       将asp.net服务器控件注册为需要在page上处理控件时引发事件的控件
                   每个page请求只能注册一个服务器控件。

                                      Sub DisplayUserName(Sender As Object, e As EventArgs)
                                         Response.Write("Welcome to " + userName.Text)
                                      End Sub
                                      Sub MyRaiseEvent(Sender As Object, e As EventArgs)
                                          Me.RaisePostBackEvent(userButton, "")
                                      End Sub
                                     Sub Page_Load(Sender As Object, e As EventArgs)
                                          Me.RegisterRequiresRaiseEvent(userButton)
                                      End Sub
                                      '一旦注册了第一个button,就可以使代码中声明的第二个button将第一个按钮的单击事件的结果发送到页

     RegisterStartupScript            允许asp.net服务器控件在page中发出客户端脚本块

                   public Sub Page_Load(Sender As Object,e As EventArgs)
                                        Dim scriptString As String  = "<script language=JavaScript> function DoClick() {"
                                         scriptString += "showMessage2.innerHTML='<h4>Welcome to Microsoft .NET!</h4>'}"
                                         scriptString += "function Page_Load(){ showMessage1.innerHTML="
                                         scriptString += "'<h4>RegisterStartupScript Example</h4>'}<"
                                         scriptString += "/"
                                         scriptString += "script>"
                                         If(Not Me.IsStartupScriptRegistered("Startup")) Then
                                              Me.RegisterStartupScript("Startup", scriptString)
                                         End If
                                      End Sub

     RegisterViewStateHandler         如果调用,则保持页视图状态
                   如果不调用该方法,页就不会计算其视图状态。服务器控件调用这种方法以计算包含它们的页的视图状态。
                   如不调用该方法,则跳过页处理的保存视图状态步骤
                   通常只有页的htmlForm服务器控件调用此方法

                                      Public Class MyForm
                                         Inherits HtmlForm
                                         Public Sub New()
                                         End Sub 'New                                                                                       

                                         <System.Security.Permissions. _
                                         PermissionSetAttribute _
                                         (System.Security.Permissions. _
                                         SecurityAction.Demand, Name:="FullTrust")> _
                                         Protected Overrides Sub OnInit(e As EventArgs)
                                            ' Save the view state if there are server controls on
                                            ' a page that calls MyForm.
                                            Page.RegisterViewStateHandler()
                                         End Sub 'OnInit
                                      End Class 'MyForm

     RenderControl                    将服务器控件的内容输出到所提供的htmltextwriter对象中,如果已启用跟踪功能,则存储有关控件的跟踪信息

                                      Override default implementation to Render children according to needs.
                                            Protected Overrides Sub RenderChildren(output As HtmlTextWriter)
                                               If HasControls() Then
                                                  Dim i As Integer
                                                  For i = Controls.Count - 1 To 0 Step -1
                                                     Controls(i).RenderControl(output)
                                                  Next
                                               End If
                                            End Sub 'RenderChildren
 
                                           Protected Overrides Sub Render(output As HtmlTextWriter)
                                               output.Write(("<br>Message from Control : " + Message))
                                               output.Write(("Showing Custom controls created in reverse" + "order"))
                                               RenderChildren(output)
                                            End Sub
                                      End Class
                   '重写自定义服务器控件中的renderchildren方法
                   '它确定当前控件的cotnrolcollection对象中是否有子控件,
                                      '有,则count属性循环访问集合,每遇到一个子控件,
                                      '它便使用rendercontrol方法将父控件及所有子控件呈现在包含页中

     受保护的属性
   ChildControlsCreated             获取一个值,指示是否已经创建服务器控件的子控件。

   Context                          获取与该页关联的httpContext对象
                   httpContext:封闭有关个别HTTP请求的所有HTTP特定的信息。

                                      Sub Page_Load(Sender As Object, e As EventArgs )
                                         Response.Write("<h3>Page.Context Example:</h3>")
                                         Context.AddError(new Exception("<font color='red'><h3>New Exception #1.</h3>"))
                                         Context.AddError(new Exception("<font color='red'><h3>New Exception #2.</h3>"))
                                         Context.AddError(new Exception("<font color='red'><h3>New Exception #3.</h3>"))
                                         Dim errs() As Exception = Context.AllErrors
                                         Dim ex As Exception
                                         For Each ex In errs
                                               Response.Write("<center><b>" + ex.ToString() + "</b></center><br>")
                                         Next
                                         Context.ClearError()
                                      End Sub

     Events                           获取控件的事件处理程序委托列表,只读
                   protected readonly property events as eventhandlerlist

 

 

     受保护的方法
     AddedControl                     在控件被添加到另一控件的controls集合后调用
                                      在控件被添加到另一控件的controls集合后,会立即调用addedControl方法

     AddParsedSubObject               通知服务器控件某个元素已经过语法分析,并将该元素添加到服务器控件的controlCollection对象
                   除非重写此方法,否则此方法自动将literalcontrol对象添加至服务器控件的controlCollection对象。

                   Public Class MyControlBuilder
                      Inherits ControlBuilder
                      Public Overrides Function GetChildControlType(tagName As String, _
                                                attributes As IDictionary) As Type
                         If String.Compare(tagName, "myitem", True) = 0 Then
                            Return GetType(TextBox)
                         End If
                         Return Nothing
                      End Function
                   End Class
                   <ControlBuilderAttribute(GetType(MyControlBuilder))> Public Class MyControl
                      Inherits Control
                      Private items As New ArrayList()
                      Protected Overrides Sub AddParsedSubObject(obj As Object)
                         If TypeOf obj Is TextBox Then
                            items.Add(obj)
                         End If
                      End Sub
                      Protected Overrides Sub CreateChildControls()
                         Dim myEnumerator As System.Collections.IEnumerator = items.GetEnumerator()
                         While myEnumerator.MoveNext()
                            Me.Controls.Add(CType(myEnumerator.Current, TextBox))
                         End While
                      End Sub
                   End Class
                   '使用addParsedSubObject方法确定在该控件的开始和结束标记间声明的元素是否为textbox
                   '如是,则将它们添加至arraylist对象

  

 

  

 

 

 

 

 


                   

 


                

 

                              
                              

     

    

 

阅读全文
0 0

相关文章推荐

img
取 消
img