【问题标题】:C# : How do i post a form to a website with some checked checkboxes?C#:如何将表单发布到带有一些选中复选框的网站?
【发布时间】:2009-12-10 10:41:33
【问题描述】:

我正在使用 C#,我想 POST 到一个有多个复选框的网站,并根据选中的复选框返回一个数据文件。

首先,我如何发布带有选中复选框的表单? 完成后,如何获取网站发送给我的数据文件?

【问题讨论】:

    标签: c# forms post web checkbox


    【解决方案1】:

    通过这个简单的 ASP 代码,我们可以看到复选框值是如何通过 POST 请求发送的:

    tst.asp

    <%
    Dim chks
    chks = Request.Form("chks")
    %>
    <html>
    <head>
        <title>Test page</title>
    </head>
    <body>
        <form name="someForm" action="" method="POST">
            <input type="checkbox" id="chk01" name="chks" value="v1" />
            <input type="checkbox" id="chk02" name="chks" value="v2" />
            <input type="checkbox" id="chk03" name="chks" value="v3" />
            <input type="submit" value="Submit!" />
        </form>
        <h3>Last "chks" = <%= chks %></h3>
    </body>
    </html>
    

    H3 行向我们展示了这一点,如果我们选中所有复选框:

    Last "chks" = v1, v2, v3
    

    现在我们知道应该如何发布数据了。使用下面的示例代码,您应该可以做到。

    C#方法示例

    using System.Text;
    using System.Net;
    using System.IO;
    using System;
    
    ...
    
    void DoIt()
    {
        String querystring = "chks=v1, v2, v3";
        byte[] buffer = Encoding.UTF8.GetBytes(querystring);
    
        WebRequest webrequest = HttpWebRequest.Create("http://someUrl/tst.asp");
        webrequest.ContentType = "application/x-www-form-urlencoded";
        webrequest.Method = "POST";
        webrequest.ContentLength = buffer.Length;
    
        using (Stream data = webrequest.GetRequestStream())
        {
            data.Write(buffer, 0, buffer.Length);
        }
    
        using (HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse())
        {
            if (webresponse.StatusCode == HttpStatusCode.OK)
            {
                /* post ok */
            }
        }
    }
    

    希望我有所帮助。

    有用的链接:

    【讨论】:

    • 很抱歉,但仍不完全清楚。假设我要发布的网页在 html-source > 我如何发布到它设置对thing1 abnd thing2的检查?
    • 您将发布“thing1=0&thing2=0”。如果选中,则发送“name=value”对。如果您有多个具有相同名称的复选框,则值以相同的“名称”发送,以逗号分隔。
    【解决方案2】:

    您需要使用 System.Net.HttpWebRequest 命名空间发出一些 WebRequest。

    您可以使用 HttpWebRequest 创建 GET 或 POST 连接。

    有一篇很棒的文章here,你也可以查看System.Net.HttpWebRequest on MSDN.

    【讨论】:

    • 但是如何勾选复选框?
    • 您需要查看随请求发送的postdata。因此,您可以使用 check=1&amp;check2=1&amp;check3=1 等信息发布到 process_page.php。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    相关资源
    最近更新 更多