How do I iterate through a form collection?

It's kind of a pain to list all of the elements from a submitted form by referring to each one individually by name, e.g.: 
 
<% 
    response.write("a = " & request.form("a") & "<br>") 
    response.write("b = " & request.form("b") & "<br>") 
    response.write("c = " & request.form("c") & "<br>") 
    ...... 
    response.write("n = " & request.form("n") & "<br>") 
%>
 
There's an easy way to manipulate this, particularly when you're troubleshooting and just want to write out all the variables to the screen (or to a comment in the page). The following code will iterate (haphazardly, mind you) through each form element: 
 
<% 
    for each x in Request.Form 
        Response.Write("<br>" & x & " = " & Request.Form(x)) 
    next 
%>
 
And in JScript: 
 
<% 
    for(f = new Enumerator(Request.Form()); !f.atEnd(); f.moveNext()) 
    { 
        var x = f.item(); 
        Response.Write("<br>" + x + " = " + Request.Form(x)); 
    } 
%>
 
What I mean by haphazardly is that, while this is a very easy way to get all of the elements in three lines, they will not be in the order you expect... they'll be all over the place, and I have yet to see a valid explanation of how the order is derived. 
 
So another way to do this iteration actually preserves the order of the original form, by cycling through the form items numerically (there is a count property of the form object). Here it is in VBScript: 
 
<% 
    for x = 1 to Request.Form.count() 
        Response.Write(Request.Form.key(x) & " = ") 
        Response.Write(Request.Form.item(x) & "<br>") 
    next 
%>
 
And in JScript: 
 
<% 
    for (x = 1; x <= Request.Form.count(); x++) 
    { 
        Response.Write(Request.Form.key(x) + " = "); 
        Response.Write(Request.Form.item(x) + "<br>"); 
    } 
%>
 
[This technique also works for the QueryString and ServerVariables collections - in the ServerVariables collection, this doesn't change anything, since they're already ordered by iteration.] 
 
Personally, I would have chosen "name" and "value" over "key" and "item." Of course, I don't have as much influence over Microsoft as some of my co-workers seem to think. :-)

你可能感兴趣的:(Collection)