问题
I'm working on a Windows Forms Application. I want the webclient to post the values from the NameValueCollection and then hit the submit button. But now it only adds the values to the html but never submits them. How can I simulate this buttonclick?
private void button2_Click(object sender, EventArgs e)
{
var requestData = new NameValueCollection
{
{"prodids", "somevalue" },
{"customerid", "somevalue" },
{"submit_button", "submit" }
};
byte[] request = client.UploadValues("myurl", "POST", requestData);
string result = Encoding.UTF8.GetString(request);
回答1:
You need to get the <form>
element that contains you button, and then get its action
attribute. That's the URL that your client should make a request to. You might need to get also the action
attribute to find out whether to make GET or POST request.
The thing is, the button itself is not important: in the web browser, if it has action "submit" it just triggers the containing form to serialize contents and send them to the action
url using `method.
When you use a client to interact with a webpage, you cannot be thinking of it like of a web browser, more like downloading a page and opening it with a text editor. Nothing's clickable, there's no JS, there's nothing even rendered - it's just the raw content sent from the server.
EDIT:
So, this is done purely with JavaScript, which is all kinds of wrong. Anyhow, your method is POST and your action is /View/DashboardProxy.php?location=Dashboard/RequestServlet&postdata=1
, so your call will be:
byte[] request = client.UploadValues("/View/DashboardProxy.php?location=Dashboard/RequestServlet&postdata=1", "POST", requestData);
Note, that the response will not be a full page, but possibly nothing or some text to put in post_result_textarea
.
Oh, and also note that there are more than 3 values passed in that POST request - values from: server_id, prodids, shopid, customerid and specialbids. Possibly the server requires all of those fields to be filled.
回答2:
You could use AJAX with WebMethod. (this example uses jQuery for the ajax requests but you could aswell do this with plan vanilla javascript)
$.post({
type: "POST",
url: /Default.aspx/methodX,
data: data,
dataType: dataType
}).done(function(data){
if (data === true) {
console.log('everything worked out fine.')
}
});
and edit your .cs file with the following.
[WebMethod]
public bool methodX(string data) {
var requestData = new NameValueCollection
{
{"prodids", "somevalue" },
{"customerid", "somevalue" },
{"submit_button", "submit" }
};
byte[] request = client.UploadValues("myurl", "POST", data);
string result = Encoding.UTF8.GetString(request);
return true;
}
or similar.. hope you get an idea from this.
Read more
http://api.jquery.com/jquery.post
https://msdn.microsoft.com/en-us/library/4ef803zd(v=vs.90).aspx
来源:https://stackoverflow.com/questions/36421487/c-sharp-click-html-button-from-webclient