Web Form 2.0 - Part 2

This post is a continuation of Web Form 2.0 - Part 1 so I suggest you read that before continuing here.  The previous post has the introduction so let's get right to it.  Normally when creating an ASP.Net form we enter markup like this:

    <asp:TextBox ID="txtCode" runat="server" />

When the user posts the form back to the server we can use the text the user entered like this:

    DoSomething(txtCode.Text);

In Part 1 I put together a simple HTML form without using the ASP.Net text box controls but because I haven't marked these controls with a runat attribute they will not be accessible from our code behind.

    <input type="text" name="code" />

    <input type="text" name="quantity" />

How then will I be able to access the values contained in these controls?  All of the form values that were passed with the request are available through the ASP.Net Request object:

Request

As you can see even the hidden input field that contains the encrypted view state is available!  The key being used in the value of the name attribute that you put on the control.  All of the values will be passed as strings so we can use them like this:

    string code = Request.Form["code"];

    int quantity = Int32.Parse(Request.Form["quantity"]);

Our example order form is probably going to want more than one row, how will this information be passed back to the user?  Remember that we are using the controls name attribute to get the data.  Controls must have unique ID attributes but names can be shared which allows us to do this to get an array of all the codes entered:

    <input type="text" name="code" />

    <input type="text" name="code" />

    <input type="text" name="code" />

RequestMultiple

    string[] codes = Request.Form["code"].Split(',');

This way we do not need to know how many rows there actually were in the table or try and figure out which ID to use to find all of the codes.  You will need to be careful what input you allow as entering a comma into a code field will cause problems.  If necessary you can generate unique names for the controls like this:

    <input type="text" name="code1" />

    <input type="text" name="code2" />

    <input type="text" name="code3" />

This will mean that you no longer get all the values in a comma separated list and will need to access them individually by their generated name.

Next time I will be looking at how to use JavaScript to generate forms with multiple rows without bloating your markup and using a lot of bandwidth, stay tuned.

Labels: , , ,

03/05/2008 07:56 PM (UTC -07:00)