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# ?

3

3 Answers 3

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)
    {

    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

NO I Cant use the runat server since the fields may be added in the client side
That's fine, you should still be able to use the aforementioned Request.Form[] to pull all posted form fields and their values.
yes i can use it, but the problem is all the field are the same name orders[] so Request.Form["orders"] will get NULL
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[].
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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.