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

前端 未结 9 1361
既然无缘
既然无缘 2021-02-09 10:06

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:32

    Have you tried fireEvent instead of RaiseEvent?

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

    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)
  • 2021-02-09 10:38

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

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

    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: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:43

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

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