不,没有直接的等价物,但如果您使用的是框架的 v3.5,您可以使用扩展方法轻松添加此功能。例如:
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)
If SessionTagDictionary.ContainsKey(TagName(ctl)) Then
SessionTagDictionary(TagName(ctl)) = tagValue
Else
SessionTagDictionary.Add(TagName(ctl), tagValue)
End If
End Sub
<Extension()> _
Public Function GetTag(ByVal ctl As Control) As String
If SessionTagDictionary.ContainsKey(TagName(ctl)) Then
Return SessionTagDictionary(TagName(ctl))
Else
Return String.Empty
End If
End Function
Private Function TagName(ByVal ctl As Control) As String
Return ctl.Page.ClientID & "." & ctl.ClientID
End Function
Private Function SessionTagDictionary() As Dictionary(Of String, String)
If HttpContext.Current.Session("TagDictionary") Is Nothing Then
SessionTagDictionary = New Dictionary(Of String, String)
HttpContext.Current.Session("TagDictionary") = SessionTagDictionary
Else
SessionTagDictionary = DirectCast(HttpContext.Current.Session("TagDictionary"), _
Dictionary(Of String, String))
End If
End Function
End Module
然后,在您的 ASP.NET 页面中,首先将您的扩展纳入范围,例如:
Imports WebApplication1.Extensions
...然后根据需要使用您的控件:
TextBox1.SetTag("Test")
Label1.Text = TextBox1.GetTag
稍后编辑:如果您真的,真的不想将标签存储在 Session 对象中,则可以将它们填充到您的 Viewstate 中。这当然意味着您的标签将在发送给用户的页面标记中公开(尽管是以模糊的形式),不幸的是,需要一些反射功能,因为页面的 ViewState 属性被标记为“受保护” ' 由于某些原因。
因此,这段代码应该仅用于娱乐目的,除非您真的想在代码审查期间引起人们的注意:
<Extension()> _
Public Sub SetTag(ByVal ctl As Control, ByVal tagValue As String)
ViewState.Add(ctl.ID & "_Tag", tagValue)
End Sub
<Extension()> _
Public Function GetTag(ByVal ctl As Control) As String
Return ViewState(ctl.ID & "_Tag")
End Function
Private Function ViewState() As Web.UI.StateBag
Return HttpContext.Current.Handler.GetType.InvokeMember("ViewState", _
Reflection.BindingFlags.GetProperty + _
Reflection.BindingFlags.Instance + _
Reflection.BindingFlags.NonPublic, _
Nothing, HttpContext.Current.CurrentHandler, Nothing)
End Function
最终编辑(我保证......)。这里有一种摆脱反射的方法:首先,创建一个新类以公开具有可用保护级别的 ViewState 属性,然后更改您的 Code-Behind (.aspx.vb) 类以继承它而不是 Web.UI。页面,例如:
Public Class PageEx
Inherits System.Web.UI.Page
Friend ReadOnly Property ViewStateEx() As Web.UI.StateBag
Get
Return MyBase.ViewState
End Get
End Property
End Class
现在,在您的扩展模块中,您可以访问这个新定义的属性:
Private Function ViewState() As Web.UI.StateBag
Return DirectCast(HttpContext.Current.Handler, PageEx).ViewStateEx
End Function
仍然有点hack,但比使用反射更容易接受......