如何触发提交按钮单击使用WebRequest的事件

时间:2016-02-08 19:17:24

标签: c# webrequest

我有以下HTML代码,我想在C#中使用WebRequest触发接受提交按钮的click事件

<form method="get" action="test">
          <input class="accept" type="submit" value="Accept">
          <input class="decline" type="button" name="decline" value="Decline">
</form>

请告诉我实现这一目标的方法。

感谢。

2 个答案:

答案 0 :(得分:0)

当您单击“接受”时,浏览器将自动向托管包含该表单的网页的服务器上的指定操作"test"发送GET请求。

GET http://example.com/test?

这是一个例子来说明“触发sumbit事件”与C#无关,但它是html的一个特性。

让我们将您的表单放入一个简单的html页面并将其保存为计算机上的某个form.html:

<html>
    <body>
        <form method="get" action="accepted.html">
            <input class="accept" type="submit" value="Accept">
            <input class="decline" type="button" name="decline" value="Decline">
        </form>
    </body>
</html>

请注意,此操作现在转到"accepted.html"。将另一个名为“accepted.html”的html文件放入与form.html相同的文件夹中。当您在浏览器中打开form.html并单击“接受”时,将显示静态页面accepted.html。 (此处您的webbrowser还充当本地文件的服务器。)

所以你的问题可能不是“如何触发提交按钮的点击事件”,而是“如何处理动态请求而不是提供静态页面”。

您希望您的网络服务器拦截GET操作'test'的请求,运行一些C#来处理它并显示结果。 这样做的一个好框架是ASP.Net MVC

答案 1 :(得分:0)

这不能通过webrequest来完成,因为它只处理.. Web请求。 这会获得像GET / POST这样的请求,但无法执行js。 如果你真的想模拟点击/等,你可以使用Webclient;

using (WebBrowser wb = new WebBrowser())
        {
            wb.Navigate("google.com");
            if (wb.Document != null)
            {
                //get your (clickable) element, for ex. the submit button.
                var el = wb.Document.GetElementById("email");
                if (el != null)
                    el.InvokeMember("click");
                else
                    Console.WriteLine("element not found!");
            }
            else
                Console.WriteLine("could not load document!");
        }

请注意,这必须在STA线程中运行。 您还可以编写一些browser-js代码来测试它。

document.GetElementById(id).click();

您可以在firefox / chrome中的控制台中运行它。

如果您必须使用网络请求,则需要转到浏览器中的页面并查看“网络”。元素检查器中的选项卡。

deserialise

然后找到POST请求并使用该链接在代码中模拟它。

有关如何使用该网址发布的一个很好的示例,请点击此处:

example

相关问题