0

I know in PHP we can easily create something like this to handle HTML array elements:

<input name="test[0]" value="1" />
<input name="test[1]" value="2" />
<input name="test[2]" value="3" />

Then in code I can access this as an array:

$arrElements = $_POST['test'];
echo $arrElements[0]; // prints: 1

I have been trying to do the same in ASP.NET (Web Applications). But unfortunately this (also) doesn't work that easy.

So if i use the same HTML as above, i then tried to do the following in my CodeBehind:

var test = Request.Form.GetValues("test");

But this results in test being null. Is there anyway to handle HTML array elements like i can with PHP?

3
  • Can u add them as server controls? and access them using ids's? Commented Feb 4, 2013 at 13:17
  • @Rajneesh No, i cannot. Commented Feb 4, 2013 at 13:24
  • Did u checkout this post stackoverflow.com/questions/8973459/… ? Commented Feb 4, 2013 at 13:27

1 Answer 1

1

Change your html :

<input name="test" value="1" />
<input name="test" value="2" />
<input name="test" value="3" />

code behind :

var test = Request.Form.GetValues("test");

And now you will get array of values in test var.

If you can't change html you can use this code :

var testList = new List<string>();
foreach (string key in Request.Form.AllKeys)
{
    if (key.StartsWith("test[") && key.EndsWith("]"))
    {
        testList.Add(Request.Form[key]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I want to be able to supply the keys like i am showing in my code. This does give me an array, but i'd like to specify the keys and also be able to even create multi dimensional arrays like: name="test[2][4]"
you should parse AllKeys collection and from it create and fill arrays, something similar like my second example. But do this only if you can't change html, if you are former PHP user in ASP.NET world don't try to bend it to be familiar as your previous tool, embrace the asp.net way and use server controls

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.