elunap elunap - 1 year ago 78
ASP.NET (C#) Question

Can't get request form from HTML form

I have a form in which I have several inputs, when I submit the form to process the information, when I try to read them I can't.

This is the form:

<form id="form1" action="page.aspx" method="get">
<input type="text" name="idP" id="idP" value="123456789" />
...
</form>


Then when I send it to "page.aspx" The url show the data:

localhost/page?idP=123456789


But when I try to read them from code as:

string[] keys = Request.Form.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}


It doesn't print anything, and AllKeys shows as 0 values, I tried with "Post" method as well but nothing.

What I'm doing wrong?

Amy Amy
Answer Source

Unlike POST and PUT, GET requests don't have a body1, so form values must be sent via the query string. You can see this in your URI: localhost/page?idP=123456789.

So, you'll need to use something like:

var idP = Request.QueryString["idP"];

Request.Form pulls values from the request body. From the documentation:

The Form property is populated when the HTTP request Content-Type value is either "application/x-www-form-urlencoded" or "multipart/form-data".

If you look at the your request headers, you'll see that Content-Type a) is missing entirely, or b) isn't either of those. So, using it here isn't appropriate.

1: Technically, GET requests can have a body, but per the HTTP specification, servers should ignore it. See this answer for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download