来自TextBox的WebControls - 不在Postaback上保存新属性

时间:2017-10-26 13:43:52

标签: c# asp.net vb.net-2010 web-controls

我觉得自己是个白痴,它应该是那么简单,但似乎它不起作用。 以下是我的控制代码。

Imports System.Web.UI.WebControls

Public Class PasswordTextBox
            Inherits TextBox
Public Sub New()
    TextMode = TextBoxMode.Password
End Sub

Public Property Password As String
    Get
        Dim s As String = CType(ViewState("Password"), String)
        If s Is Nothing Then Return ""
        Return s
    End Get
    Set(value As String)
        ViewState("Password") = value
    End Set
End Property

Private Const DEFAULT_PASSWORD As String = "********************"
Public Overrides Property Text() As String
    Get
        If Password = "" Then Return ""
        Return DEFAULT_PASSWORD
    End Get
    Set
        MyBase.Text = DEFAULT_PASSWORD
        Attributes("value") = DEFAULT_PASSWORD
    End Set
End Property

Protected Overrides Sub OnPreRender(e As EventArgs)
    MyBase.OnPreRender(e)

    Attributes("value") = Text
End Sub
Protected Overrides Sub Render(ByVal output As System.Web.UI.HtmlTextWriter)
    MyBase.Render(output)
End Sub

结束班

目的很简单,要覆盖属性以始终显示*****作为值,而是使用新属性Password来获取/设置数据。因此,当用户使用浏览器中的“Inspect element”功能时,他无法获得实际密码。

但是,在页面回发时,当我获得txtPassword.Password属性时,它返回一个空字符串。

我有什么遗失的吗? 谢谢

1 个答案:

答案 0 :(得分:0)

好的,我能找到问题。我必须从IPostBackDataHandler继承,然后重写LoadPostData方法。

新课程如下所示。

Imports System.Web.UI
Imports System.Web.UI.WebControls


Public Class PasswordTextBox
      Inherits TextBox
      Implements IPostBackDataHandler

Public Sub New()
    TextMode = TextBoxMode.Password
End Sub

Public Property Password As String
    Get
        Dim s As String = CType(ViewState("Password"), String)
        If s Is Nothing Then Return ""
        Return s
    End Get
    Set(value As String)
        ViewState("Password") = value
    End Set
End Property

Private Const DEFAULT_PASSWORD As String = "********************"
Public Overrides Property Text() As String
    Get
        If Password = "" Then Return ""
        Return DEFAULT_PASSWORD
    End Get
    Set
        MyBase.Text = DEFAULT_PASSWORD
        Attributes("value") = DEFAULT_PASSWORD
    End Set
End Property

Protected Overrides Sub OnPreRender(e As EventArgs)
    MyBase.OnPreRender(e)

    Attributes("value") = Text
End Sub
Protected Overrides Sub Render(ByVal output As System.Web.UI.HtmlTextWriter)
    MyBase.Render(output)
End Sub

Public Overridable Shadows Function LoadPostData(postDataKey As String, postCollection As System.Collections.Specialized.NameValueCollection) As Boolean Implements IPostBackDataHandler.LoadPostData
    Dim presentValue As String = Password
    Dim postedValue As String = postCollection(postDataKey)

    If presentValue Is Nothing OrElse Not presentValue.Equals(postedValue) Then
        If postedValue <> DEFAULT_PASSWORD Then Password = postedValue
        Return True
    End If

    Return False
End Function

End Class