来自 TextBox 的 WebControls - 不在 Postaback 上保存新属性
Posted
技术标签:
【中文标题】来自 TextBox 的 WebControls - 不在 Postaback 上保存新属性【英文标题】:WebControls From TextBox - Not Saving New Property on Postaback 【发布时间】:2018-04-07 22:29:16 【问题描述】:我觉得自己是个白痴,应该就这么简单,但似乎行不通。 下面是我的控制代码。
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】:好的,我能够找到问题所在。我必须从 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
【讨论】:
以上是关于来自 TextBox 的 WebControls - 不在 Postaback 上保存新属性的主要内容,如果未能解决你的问题,请参考以下文章
System.Web.UI.WebControls.TextBox”不包含“text”的定义,并且找不到可接受类型为“System.Web.UI.Web
将asp.net(c#)中textbox的内容导出到word中
Windows 7和Windows XP中的TextBox之间是否存在根本差异