Picking specific parts out of a query string - asp.net

I have a query string which has more than one value being passed through it and I need to access the second passed value... I have this as of now:
If Request.QueryString("ANBOS") IsNot Nothing Then
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim index As Integer = url.IndexOf("-")
If index > 0 Then
url = url.Substring(0, index)
End If
DBTable = MaterialStuff.GetComponentsForMaterial(CInt(Request.QueryString(url)))
I'm attempting here to dumb everything after the first value I need, then go back and look at the query string where it's equal to ANBOS and get its value, but when I go get the value of it, the whole query string is still there, both values...
How do I make it so I just get the first value? Any help is greatly appreciated :)
Edit: Query String being passed through
Response.Redirect("Edit.aspx?ANBOS=" & CType(flxSearchResults.SelectedItem.Cells(1).Text, Integer) & "MaterialNumberToUpdate=" & NextMaterialID)

Your query string is being generated incorrectly
Response.Redirect("Edit.aspx?ANBOS=" & CType(flxSearchResults.SelectedItem.Cells(1).Text, Integer) & "MaterialNumberToUpdate=" & NextMaterialID)
should be..
Response.Redirect("Edit.aspx?ANBOS=" & CType(flxSearchResults.SelectedItem.Cells(1).Text, Integer) & "&MaterialNumberToUpdate=" & NextMaterialID)
This is because the query string uses ampersand signs (&) to separate key value pairs.

Related

How to get my params value with a & in the URL?

www.myurl.com?param1=123&param2=456 OK
www.myurl.com?param1=123&param2=456 NOT OK
In my vb code behind, with the second URL, I get the value of param1 only.
Me.Page.Request("param1") : value OK
Me.Page.Request("param2") : value 0
Firstly, I would advise rethinking how your URL is built with a view to removing the need for an & it will be far easier for you.
If this is not possible for whatever reason, you will need to extract the parameter values from the querystring yourself.
One possible solution:
Dim url As String = Request.RawUrl
Dim urlParams As String() = url.Split("?"C)
If urlParams.Length > 1 Then
Dim parameters As String() = urlParams(1).Split(New String() {"&"}, StringSplitOptions.None)
For Each param As var In parameters
' will give you the paramater value
Dim value As String = param.Split("="C)(1)
Next
End If

The given key was not present in the dictionary. VB.NET

I'm trying to debug an issue I didnt create and I'm getting the generic error "The given key was not present in the dictionary." Here is the code:
Dim myInfo As New Dictionary(Of Integer, String)
For i As Integer = 0 To Region.GetRegionCount - 1
myInfo.Add(i, Server.HtmlEncode(ContentItem.Properties("StoreInfoRegion" & i).Value.ToString))
Next
Session(SESSION_INFO) = myInfo
When I step thru it the error occurs on the call to "Add", I guess Im confused because it's adding a key not trying to access one.
Thanks!
You have a pretty big line of code, split it up into it's pieces and you might find where the problem is exactly.
Instead of
myInfo.Add(i, Server.HtmlEncode(ContentItem.Properties("StoreInfoRegion" & i).Value.ToString))
Have
Dim propertyValue As String
propertyValue = ContentItem.Properties("StoreInfoRegion" & i).Value.ToString
propertyValue = Server.HtmlEncode(propertyValue)
myInfo.Add(i, propertyValue)
With this change, I'm pretty sure that you will see the error on the 2nd line where you fetch the value of Properties. This mean you do not have a value for "StoreInfoRegion" & i
You could do
If ContentItem.Properties.ContainsKey("StoreInfoRegion" & i) Then
Dim propertyValue As String
propertyValue = ContentItem.Properties("StoreInfoRegion" & i).Value.ToString
propertyValue = Server.HtmlEncode(propertyValue)
myInfo.Add(i, propertyValue)
End If
But I think you should first understand why there are no value for that key first.

Separating values in a textbox by special character

I have an asp.net/vb.net web app that requires information to be put into a multiline text box. If the user hits enter while in the textbox it drops down to next line, and they can enter more data in. When it tries to go to the database it fails because of the way the data is represented. I need help with looping through the field and getting each value.
This is how the data is represented in the DataTable
0;0.123;0.234;0.345;...
I need each value between the ; character... so I was thinking something like this?
If dbRow.Item("PV").ToString.Contains(";") Then
For Each symbol As String In DBTable.Rows
'get data b/w the ';'
Next
End If
Any help would be greatly appreciated
Edit:
If dbRow.Item("PV").ToString.Contains(";") Then
For Each s As String In dbRow.Item("PV").ToString
Dim fields() As String = s.Split(";"c)
For Each value As String In fields
.Append("'" & CDbl(value) & "'," & "SysDate,1)")
DBCommand.CommandText = myInsertIntoProperty_DataStringBuilder.ToString
DBCommand.ExecuteNonQuery()
myInsertIntoPropertyStringBuilder = New StringBuilder
Next
Next
Else
.Append("'" & CDbl(dbRow.Item("PV")) & "'," & "SysDate,1)")
End If
You mean something like this?
Dim s As String In dbRow.Item("PV").ToString()
Dim fields() As String = s.Split(";"c)
For Each value As String In fields
' Do what you want with the value
Next
Then access each value with field(0), fields(1), etc. You can then convert it to the appropriate type, for example:
Dim value As Double = Double.Parse(fields(0), CultureInfo.InvariantCulture)

Getting values from any URL

I have this url : http://localhost:49500/Learning/Chapitre.aspx?id=2
How can I get just the value of id in this url ?
You can access all the query strings through the Request.QueryString() array:
Request.QueryString("id") will give you the 2
Despite my own comment saying it has been answered, here is the code.
Dim idval As String = System.Web.HttpUtility.ParseQueryString("http://localhost:49500/Learning/Chapitre.aspx?id=2")("id")
Create a new instance of System.Uri class with the URL and the use the Query property to get the query string part.
Once you have that string, do String.Split on the '&' character. For each string in the resulting array, do String.Split on the '=' char. In the resulting array, the first string is the query parameter name, the second is the value (if present). Check if the name is the one you are interested in and if it is, get the value.
Update: Boy, I haven't touched VB since 1999... :-)
Here's the code for my answer. I didn't realize that the Url you want to parse is the page Url. For that specific case, Request.QueryString("id") will indeed be a better solution.
Dim url As Uri = New Uri("http://localhost:49500/Learning/Chapitre.aspx?id=2")
Dim query As String = url.Query.Trim("?")
Dim parameters() As String = query.Split("&")
Dim tokens() As String
Dim value As String = ""
For index As Integer = 0 To parameters.Length - 1
tokens = parameters(index).Split("=")
If tokens(0).ToLower = "id" Then
If tokens.Length = 2 Then
value = tokens(1)
End If
Exit For
End If
Next
' At this point value contains the parameter value or
' is empty if the parameter has no value or if the parameter is not present
You can use Request vb method
Using the url : http://localhost:49500/Learning/Chapitre.aspx?id=2
Dim valueId = Request("id")
to test the code:
response.Write(valueId)
value Id is 2

Getting the Request Variables from an ASP.NET page

I wrote the following function that works about 95% of the time, but I need it to work 100% (obviously):
Public Shared Function getPassedVars() As String
Const keyCount As Integer = 54 ' 54 seems to be the number of parameter keys passed by default (for this web_app).
' there are more if there is a form involved (ie. from search page)
Dim oParams As String = ""
Try
With HttpContext.Current
If .Request.Params.AllKeys.Count > keyCount Then
For i As Integer = 0 To (.Request.Params.AllKeys.Count - (keyCount + 1))
oParams &= String.Format("{0}={1}{2}", .Request.Params.Keys.Item(i), .Request.Params(i), IIf(i < .Request.Params.AllKeys.Count - (keyCount + 1), ";", ""))
Next
End If
End With
Return oParams
Catch ex As Exception
Return Nothing
End Try
End Function
It scrubs the Request.Params object for passed variables, which are in the beginning of the array (the remaining ones are ASP parameters). I am pretty sure I've seen a different way to get these parameters, but I haven't been able to figure it out. Any suggestions?
EDIT
So it looks like I can use the Request.URL.Query to achieve this, I will investigate this and post back.
Here is what I came up with:
Public Shared Function getPassedVars() As String
Dim oParams As String = ""
Dim qString As String = ""
Dim oSplit As New List(Of String)
Try
With HttpContext.Current
qString = .Request.Url.Query
If qString.Length > 0 Then 'do we have any passed variables?
If qString.StartsWith("?") Then qString = qString.Remove(0, 1) 'remove leading ? from querystring if it is there
oSplit.AddRange(qString.Split("&"))
For i As Integer = 0 To oSplit.Count - 1
oParams &= String.Format("{0}{1}", oSplit.Item(i), IIf(i < oSplit.Count - 1, ";", ""))
Next
Return oParams
Else
Return Nothing
End If
End With
Catch ex As Exception
Return Nothing
End Try
End Function
So far so good.
Request.QueryString is a NameValueCollection, so the easiest way to get the "parameters" is to do the following:
foreach (String s in Request.QueryString) {
Response.Write(s + " = " + Request.QueryString[s]);
}
Where is your function located? If it's executing in the page's code behind then you definitely do not need to use the HttpContext variable.
It looks like you are trying to get values from the query string.
For example, for this URL:-
http://www.tempuri.org/mypage.aspx?param1=x&param2=y
I assume you want retreive the values of the query string parameters param1 and param2?
If so, just use:-
Dim param1 as String = Request.QueryString("param1")
Otherwise, if these parameters are contained in a form (an HTTP POST request) then use the method which Mitchel Sellers suggests.
If you know the name you can use the following to get it by key value
Dim myParamValue as String = Request.Form("MyKeyName")
Otherwise, you can loop through the form collection, by key etc, to get the values. The key is, do you really need to be parsing all 54 items? Or are you simply looking for a few specific values?
httpcontext.Current.Request.QueryString("KeyName")
Request.Params will contain the query parameters you're after.
There's no need to parse the info from Request.URL since it's already done for you.

Resources