Handling arrays of HTML input elements using Request.Form, like PHP

How can I get this entry array on asp.net correctly?

<input type=hidden name='field[name][]' value='alex' /> <input type=hidden name='field[name][]' value='mark' /> <input type=hidden name='field[name][]' value='helen' /> <input type=hidden name='field[age][]' value='22' /> <input type=hidden name='field[age][]' value='30' /> <input type=hidden name='field[age][]' value='29' /> 

In php you can access the field $field = $_POST["field"]

$field["name"] and $field["age"] are just arrays containing names and ages.

+6
source share
3 answers

You can use standard line breaks - that's all php does for you behind the scenes. PHP is not a strongly typed language, but this means that it is much easier for them to provide the "look" of this function.

The reality is that php just allows you to enter comma-delimited input and automatically splits it into you.

So ... if you want to do this in asp.net, you can use the same input name several times and it will be returned with the request object as a comma-separated list. I would not recommend using this approach for user input, but it will work fine if you control the input, for example, combining a list with hidden input from a jquery script.

To understand what is happening (with php too .. all dev web technologies use the same http rules), just try submitting the form using input (don't install the runat server), which exists twice.

 <input type="text" name="MyTest" value="MyVal1" /> <input type="text" name="MyTest" value="MyVal2" /> 

In pageload add this

 if(IsPostBack) { Response.Write(Request["MyTest"]); } 

You should see

MyVal1, MyVal2

On the screen.

Now, if you want it to be in an array, you can:

 string[] myvals = Request["MyTest"].Split(','); 

if you want integers or other data types (php doesn't know / doesn't care which data type really is), you will have to skip it and parse into another array / general list.

I don’t know what you want as the end result, but understanding what the browser sends back is the first step, and the short answer is ...

Yes, ASP.NET can do this (a little more manually).

+4
source share

in fact, it exists with asp.net. - you can use

 string[] MyTest = Request.Form.GetValues("MyTest"); 

or

 string[] MyTest = Request.QueryString.GetValues("MyTest"); 
+27
source share

These are not input arrays. HTML has no concept of arrays.

These are just input groups with the same name.

What are you trying to achieve? Why aren't you using server-side controls?


Update:

You can access the Request.Forms collection - it will contain the hosted form elements.

Use server controls as an alternative - you can access them by identifier.

0
source share

All Articles