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

前端 未结 9 1559
梦谈多话
梦谈多话 2021-02-09 09:57

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 targe

相关标签:
9条回答
  • 2021-02-09 10:33

    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");
    
    0 讨论(0)
  • 2021-02-09 10:36

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

    0 讨论(0)
  • 2021-02-09 10:43

    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");
    
    0 讨论(0)
  • 2021-02-09 10:45

    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.

    0 讨论(0)
  • 2021-02-09 10:45

    Have you tried fireEvent instead of RaiseEvent?

    0 讨论(0)
  • 2021-02-09 10:46

    Just a possible useful extra where the submit button has not been given an Id - as is frequently the case.

        private HtmlElement GetInputElement(string name, HtmlDocument doc) {
                HtmlElementCollection elems = doc.GetElementsByTagName("input");
    
                foreach (HtmlElement elem in elems)
                {
                    String nameStr = elem.GetAttribute("value");
                    if (!String.IsNullOrEmpty (nameStr) && nameStr.Equals (name))
                    {
                        return elem;
                    }
                }
                return null;
        }
    

    So you can call it like so:

     GetInputElement("Login", webBrowser1.Document).InvokeMember("Click");
    

    It'll raise an exception if the submit input with the value 'Login', but you can break it up if you want to conditionally check before invoking the click.

    0 讨论(0)
提交回复
热议问题