How to click a button on an ASP.NET web page progr

2020-06-04 03:51发布

I am trying to figure out how to click a button on a web page programmatically.

Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded:

HtmlDocument doc = webBrowser1.Document;

HtmlElement userID = doc.GetElementById("userIDTextBox");
userID.InnerText = "user1";

HtmlElement password = doc.GetElementById("userPasswordTextBox");
password.InnerText = "password";

HtmlElement button = doc.GetElementById("logonButton");
button.RaiseEvent("onclick");

This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given.

BTW The button is coded:

<input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" />

标签: asp.net
9条回答
三岁会撩人
2楼-- · 2020-06-04 03:51

try this button.focus System.Windows.Forms.SendKeys.Send("{ENTER}")

查看更多
趁早两清
3楼-- · 2020-06-04 03:58

There is an example of how to submit the form using InvokeMember here. http://msdn.microsoft.com/en-us/library/ms171716.aspx

查看更多
爷的心禁止访问
4楼-- · 2020-06-04 04:01

var btn = document.getElementById(btnName); if (btn) btn.click();

查看更多
神经病院院长
5楼-- · 2020-06-04 04:01

You posted a comment along the lines of not wanting to use a client side script on @Phunchak's answer. I think what you are trying to do is impossible. The only way to interact with the form is via a client side script. The C# code can only control what happens before the page is sent out to the browser.

查看更多
做自己的国王
6楼-- · 2020-06-04 04:02

You can try and invoke the Page_ClientValidate() method directly through the clientscript instead of clicking the button, let me dig up an example.

Using MSHTML

mshtml.IHTMLWindow2 myBroserWindow = (mshtml.IHTMLWindow2)MyWebBrowser.Document.Window.DomWindow;
myBroserWindow.execScript("Page_ClientValidate();", "javascript");
查看更多
太酷不给撩
7楼-- · 2020-06-04 04:07

How does this work? Works for me

HtmlDocument doc = webBrowser1.Document;

doc.All["userIDTextBox"].SetAttribute("Value", "user1");
doc.All["userPasswordTextBox"].SetAttribute("Value", "Password!");
doc.All["logonButton"].InvokeMember("Click");
查看更多
登录 后发表回答