I was trying to fetch the Name/Value of a querystring using For Each loop, as per @kloarubeek answer shown in → Request.Querystring(variablevalue) possible? as follows:
For Each Item in Request.QueryString
Response.Write Item & ": " & Request.QueryString(Item) & "<br/>"
Next
But it returns the items not in the order sent, for example:
if my queryString is:
"Item1=1&Item2=2&Item3=3&Item4=4"
then the For Each Loop returns:
Item1=1
Item3=3
Item2=2
Item4=4
I managed to work around it by splitting it into an Array and then loop inside this array and re-split each item again into name and value. but it's a long and not very efficient coding.
So is there a better and shorter way to fetch the querystring's name/value using the For Each Loop but in the same order?
Your
for eachstatement should loop through the query strings in the order they were passed, it's very strange that it doesn't, I'd never heard of that before. But as your parameters are numbered you can assign them to an array and reorder based on their numerical indicators.This is how I would tackle this issue, I don't know if it's shorter than your method of splitting and reordering, but it does seem to be efficient:
Let's take a completely jumbled up query string order:
Output:
Let's do the same, but throw in some additional parameters:
Output:
The additional parameters are ignored
Finally, let's pass some duplicate parameters:
Output:
EDIT: I assumed the fault was with IIS or ASP reordering the querystring header (somehow?), but after seeing your comment where you said
if I target the querystring with the index number it gets the order rightthe headers are obviously correct and the fault lies within thefor eachmethod (as outlined in the other answer). A much simpler solution would be to split the raw querystring header yourself (rather than usingfor each) and loop through looking for the items: