Submit a form and controls programmatically using C#

How can I submit a form to a URL programmatically using C# and render the response to the browser ?

The form has one <input tag which I need to set in code. The remote site is expecting the form as POST and with the form <input text box supplied.

Once the site receives the request it will send a response back which will be HTML.

I think I know how to send a HttpWebRequest but I don't know how to submit a form field in the POST.

Any ideas please?
Who is Participating?
meetingexpectationsConnect With a Mentor Commented:
Here is in VB...

Dim strHeaderVars As String = String.Empty

				Dim strEmailAddress As String = String.Empty & txtEmailAddress.Text
				Dim strFirstName As String = String.Empty & txtFirstName.Text
				Dim strLastname As String = String.Empty & txtLastname.Text
                Dim strPostToPage As String = "http://yourURL you want to post to"
				strHeaderVars = "sevfld_1=" & strEmailAddress _
							& "&sevfld_3=" & strFirstName _
							& "&sevfld_4=" & strLastname _
							& "&sevfld_5=" & strCompany 				            
				Dim bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(strHeaderVars)
				Dim reqWebRequest As HttpWebRequest = DirectCast(WebRequest.Create(strPostToPage), HttpWebRequest)
				reqWebRequest.Method = "POST"
				reqWebRequest.ContentType = "application/x-www-form-urlencoded"
				reqWebRequest.ContentLength = bytes.Length

				Using requestStream As IO.Stream = reqWebRequest.GetRequestStream()
					requestStream.Write(bytes, 0, bytes.Length)
				End Using

				Using response As HttpWebResponse = DirectCast(reqWebRequest.GetResponse(), HttpWebResponse)
					If response.StatusCode <> HttpStatusCode.OK Then
						Dim strMessage As String = String.Format("POST to " & strPostToPage & " failed. Received HTTP {0}", response.StatusCode)
						Throw New Exception(strMessage)
                                                  End If
                                          End If

                End Using

Open in new window

jonatecAuthor Commented:
Yes that will do nicely thanks, I converted to C# ok.
All Courses

From novice to tech pro — start learning today.