此函数将使您对QueryString拥有100%的控制权-非常适合经常使用QueryString操作的程序员。
当我不得不更改QueryString的值并删除一些值,添加一些值等时,我编写了此函数。
它需要四(4)个参数:
oldUrl =您要操作的当前QueryString
qsName =您要修改/删除/添加的QueryField的名称
newValue =您想要QueryField的新值。 如果删除则设置为“”
del =可选的整数位标志; 如果设置为1,它将从QueryString中删除QueryField / QueryFieldValue。
这是代码,请尽情享受! (我总是欢迎提出新建议)
Function ChangeValue(ByVal oldUrl As String, ByVal qsName As String, ByVal newValue As String, Optional ByVal del As Integer = 0) As String
Dim newUrl As String = ""
' Check if the [qsName] is currently in the [oldUrl]
If InStr(oldUrl, qsName & "=")
oldUrl += "&"
Dim pos1 As Integer, pos2 As Integer
If del = 1
pos1 = oldUrl.IndexOf(qsName & "=")
pos2 = oldUrl.IndexOf("&", pos1) + 1
Else
pos1 = oldUrl.IndexOf(qsName & "=") + qsName.Length + 1
pos2 = oldUrl.IndexOf("&", pos1)
End If
Dim chunk_1 As String = oldUrl.SubString(0, pos1)
Dim chunk_2 As String = oldUrl.SubString(pos2)
If del = 1
newUrl = chunk_1 & chunk_2
Else
newUrl = chunk_1 & newValue & chunk_2
End If
newUrl = newUrl.SubString(0, (newUrl.Length - 1))
Else
If del = 1
Return oldUrl
End If
' Append the new value to the [oldUrl] and make it a [newUrl]
If oldUrl.EndsWith("?")
newUrl = oldUrl & qsName & "=" & newValue
ElseIf InStr(oldUrl, "?") AndAlso oldUrl.EndsWith("?") = False
If oldUrl.EndsWith("&")
newUrl = oldUrl & qsName & "=" & newValue
Else
newUrl = oldUrl & "&" & qsName & "=" & newValue
End If
Else
newUrl = oldUrl & "?" & qsName & "=" & newValue
End If
End If
Return newUrl
End Function
这是一个例子:
我们有查询字符串
http://www.yourdomain.com/search.aspx?fulltext=cat&author=bill+nye&type=scientist&age=45
现在,我想将“全文”更改为“ dog”,将“作者”更改为“ bob dole”
另外,我想从QueryString中删除“类型”。
Dim newUrl = Request.RawUrl.ToString()
newUrl = ChangeValue(newUrl, "fulltext", "dog")
newUrl = ChangeValue(newUrl, "author", "bob dole")
newUrl = ChangeValue(newUrl, "type", "", 1)
QueryString现在看起来像这样:
http://www.yourdomain.com/search.aspx?fulltext=dog&author=bob+dole&age=45
是!
就这么简单!
From: https://bytes.com/topic/asp-net/insights/697741-querystring-manipulation-using-vb-net