开发者

HTTP post form using c# - post name of form as well

开发者 https://www.devze.com 2023-02-07 10:32 出处:网络
I\'m using the following code to POST data to a URL on button click. I need to be able to send a form name along with this data. Any suggestions?

I'm using the following code to POST data to a URL on button click. I need to be able to send a form name along with this data. Any suggestions?

string url = "http://www.someurl.com";
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    string proxy = null;

    string data = String.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}&{8}={9}&{10}={11}", 
                    txtName.ClientID, txtName.Text, 
                    txtEmail.ClientID, txtEma开发者_开发知识库il.Text,
                    txtLanguages.ClientID, txtLanguages.Text,
                    txtPhone.ClientID, txtPhone.Text,
                    txtAdditional.ClientID, txtAdditional.Text);
    byte[] buffer = Encoding.UTF8.GetBytes(data);

    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    req.ContentLength = buffer.Length;
    req.Proxy = new WebProxy(proxy, true); // ignore for local addresses 
    req.CookieContainer = new CookieContainer(); // enable cookies 

    Stream reqst = req.GetRequestStream(); // add form data to request stream 
    reqst.Write(buffer, 0, buffer.Length);
    reqst.Flush();
    reqst.Close();


If you mean the action, just append it to the URL.


You can append any key/value pair you want to the POST data - doesn't matter whether it's a control name, form name, form action or nowhere on the page at all.

By the way, if you're going to construct POST data manually you should URL-encode the values, eg.

string data = String.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}&{8}={9}&{10}={11}", 
                txtName.ClientID, HttpUtility.UrlEncode(txtName.Text),
                ...


If you are managing different activities with different forms, you could also send a hidden variable, between your form with the kind of activity you are doing, so you can evaluate the hidden hidden value, and act acording to it.

Or put a value and name to the submit button... it will come to your script as apost variable as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号