views:

256

answers:

2

I'm working in C#, and I want to POST to a website that has multiple checkboxes and returns a datafile depending on which checkboxes are checked.

First of all, how do I post a form with checked checkboxes ? And once that is done, how do I get the datafile the site sends me ?

+1  A: 

You'll want to make some WebRequests using the System.Net.HttpWebRequest namespace.

You can create a GET or a POST connection with HttpWebRequest.

There's a great article on it here and you can also check out System.Net.HttpWebRequest on MSDN.

Daniel May
But how do I check checkboxes ?
Pygmy
Daniel May
+1  A: 

With this simple ASP code, we can see how checkboxes values are sent through a POST request:

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>

The H3 line show us this, if we check all the checkboxes:

Last "chks" = v1, v2, v3

Now we know how the data should be posted. With the sample code below, you should be able to do it.

C# method sample

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 */
        }
    }
}

Hope I've helped.

Useful links:

Ricardo Nolde
I'm sorry but it's still not completely clear.Suppose the webpage I want to post to has in the html-source< input type='checkbox' value='0' name='thing1' checked='checked' / >< input type='checkbox' value='0' name='thing2' checked='checked' / >< input type='checkbox' value='0' name='thing3' checked='checked' / >How do I post to it setting checks for thing1 abnd thing2 ?
Pygmy
Ricardo Nolde