在Web开发中,表单数据的处理是一个常见的需求。为了提高表单数据的处理效率,开发了一个工具类,它将表单数据视为一个强类型的可编辑集合。这个工具类不仅简化了数据的读取和处理,还提供了数据在页面间传递的便利。
这个工具类提供了以下主要功能:
创建了一个测试页面,允许用户通过GET或POST方法提交表单数据。用户可以选择使用Response.Redirect方法通过GET方式重定向,或者使用Server.Transfer方法配合TLS在页面间传递数据。
代码实现非常简单,但功能强大。以下是一些关键的实现方法:
Imports System.Collections.Specialized
Imports System.Text
Imports System.Threading
Public Class HttpFormUtil
Inherits System.Object
Private fc As New NameValueCollection
Private sActionPage As String
Public Sub Add(ByVal sKeyName As String, ByVal sValString As String)
If Not fc.Item(sKeyName) Is Nothing Then
fc.Remove(sKeyName)
End If
fc.Add(sKeyName, sValString)
End Sub
Public Function Count() As Integer
Return fc.Count()
End Function
Public Sub Remove(ByVal sKeyName As String)
If Not fc.Item(sKeyName) Is Nothing Then
fc.Remove(sKeyName)
End If
End Sub
Public Function Lookup(ByVal sKeyName As String) As String
Dim sValueString As String
sValueString = fc.Item(sKeyName)
If sValueString Is Nothing Then
sValueString = String.Empty
End If
Return sValueString
End Function
Public Sub BuildFromPostRequest()
fc = New NameValueCollection(System.Web.HttpContext.Current.Request.Form)
End Sub
Public Sub BuildFromGetRequest()
fc = New NameValueCollection(System.Web.HttpContext.Current.Request.QueryString)
End Sub
Public Sub BuildFromTls()
Dim dataSlot As LocalDataStoreSlot
Dim retrievedData As Object
dataSlot = Thread.GetNamedDataSlot("passedData")
retrievedData = Thread.GetData(dataSlot)
Try
If retrievedData Is Nothing Then
' do nothing
Else
fc = CType(retrievedData, NameValueCollection)
End If
Catch ex As Exception
' treat collection has having nothing in it.
fc = New NameValueCollection
Finally
Try
Thread.FreeNamedDataSlot("passedData")
Catch ex As Exception
End Try
End Try
End Sub
Public Function ToPostForm() As String
Dim iCurrElem As Integer
Dim sb As New StringBuilder
Remove("submit")
For iCurrElem = 0 To fc.Count - 1
sb.Append("")
Next
Return sb.ToString()
End Function
Public Function ToQueryString() As String
Dim sb As New StringBuilder
Dim oPageContext As System.Web.HttpContext
Dim iCurrElem As Integer
oPageContext = System.Web.HttpContext.Current
Remove("submit")
For iCurrElem = 0 To fc.Count - 1
If iCurrElem = 0 Then
sb.Append("?")
Else
sb.Append("&")
End If
sb.Append(oPageContext.Server.UrlEncode(fc.Keys(iCurrElem)))
sb.Append("=")
sb.Append(oPageContext.Server.UrlEncode(fc.Get(iCurrElem)))
Next
Return sb.ToString()
End Function
Public Sub ToTls()
Dim dataSlot As LocalDataStoreSlot
Remove("submit")
Thread.AllocateNamedDataSlot("passedData")
dataSlot = Thread.GetNamedDataSlot("passedData")
Thread.SetData(dataSlot, fc)
End Sub
Public Function ToDictionary() As Dictionary(Of String, String)
Dim oList As New Dictionary(Of String, String)
For Each currEntry As String In fc.AllKeys
oList.Add(currEntry, fc(currEntry))
Next
Return oList
End Function
End Class