8

I have a dynamic form that allow to add many fields dynamically,

I Know how to get the value of single field in aspnet using : Request.Form["myField"],but here i have more than field and i dont know the count of these fields since these are dynamic

the fields name is "orders[]"

ex:

<form>
<input type="text" name="orders[]" value="order1" />
<input type="text" name="orders[]" value="order2" />
<input type="text" name="orders[]" value="order3" />
</form>

In php, i get the values as an array by accessing $_POST['orders'];

ex:

$orders = $_POST['orders'];
foreach($orders as $order){
 //execute ...
}

how can I do this in c# ?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
amd
  • 20,637
  • 6
  • 49
  • 67

3 Answers3

10

Use Request.Form.GetValues.

Request.Form is a NameValueCollection, an object that can store a collection of items under the same key and the ToString displays the values in CSV format.

Markup:

<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />

<asp:Button Text="text" runat="server" OnClick="ClickEv" />

Code behind:

protected void ClickEv(object sender, EventArgs e)
{
    var postedValues = Request.Form.GetValues("postField[]");

    foreach (var value in postedValues)
    {

    }
}
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
3

You would use Request.Form[]. Or if your form and fields had runat="server" and ids, you could just use the id in the codebehind and the .Text() method to access its value.

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
  • 1
    NO I Cant use the runat server since the fields may be added in the client side – amd Mar 31 '12 at 13:23
  • That's fine, you should still be able to use the aforementioned `Request.Form[]` to pull all posted form fields and their values. – Code Maverick Mar 31 '12 at 13:32
  • yes i can use it, but the problem is all the field are the same name `orders[]` so Request.Form["orders"] will get NULL – amd Mar 31 '12 at 13:35
  • You really should expand on why you are using ASP.NET WebForms and C#, yet not taking advantage of it's default functionality such as forms that are `runat="server"` that use ASP.NET WebControls with IDs and runat="server" so you can simply access them in the code-behind via their IDs. To answer your comment, you need to put an `ID` attribute on each input to access it via `Request.Form[]`. – Code Maverick Mar 31 '12 at 13:39
  • I mentioned above that the fields are dynamic,so the fields are generated at the client side,every time the number of fields will be different,in this scenario there is no way to use the server side controls – amd Mar 31 '12 at 14:21
1

You can access everything that gets sent back to the server by using the Request object.

Request.Form.Items

Is a collection that will contain the item you are looking for.

Darren
  • 68,902
  • 24
  • 138
  • 144