Using C# to iterate form fields with same name

I have a section of a form that I need to handle differently from the rest of form results. In the section that needs special handling I need to iterate over 3 form fields that have the same name. They have to have the same name, I can't change it. The section of the form I am referring to looks something like this:

<td><input name="Color" size="20" value="" type="text"></td>
<td><input name="Color" size="20" value="" type="text"></td>
<td><input name="Color" size="20" value="" type="text"></td>

Using C# I try something like this:

I try to handle it like this:

int i;

for (i = 1; i <= Request.Form["Color"][i]; i++)
{
    colorName.Text += Request.Form["Color"];
}

Which leads to the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.

How should I be handling form fields with the same name?

Answers


You don't need to do any splits or other special magic; you can simply get a string array from ASP.NET:

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


I would suggest adding each form to a list and using the ForEach operator instead, although it's a bit more longwinded than what you're already trying to do.

e.g.

private List<Request.Form> newList = new List<Request.Form>();

newList.Add(FormName1);
newList.Add(FormName2);
newList.Add(FormName3);

foreach(Request.Form form in newList)
{
   //perform logic
}

Note: I'm assuming that Request.Form is the class name for the Form itself.

I've not tested this myself so there might be a few errors in it, hope it helps to a degree anyway.


It is important to remember that the form values posted is nothing more than a name/value collection, where the value is a simple string. So it does not make much sense to have multiple form fields with the same name. I don't even know whether it is actually allowed.

But as you say, you cannot change that. I performed a quick test in IE and Chrome, and at least in these browsers, it seems that they send multiple form fields with the same name as a comma-separated string. You might want to test some more to make sure this behaviour is consistent across browsers.

With that in mind, you could say:

string colorValues = Request.Form["Color"];
string [] colors = colorValues.Split(',');

Each element in the colors array now corresponds to the value of each input element that was posted.


Either Request.Form["Color"] is null, or colorName is not found on the aspx page. I can't tell which based on your code. Otherwise, it looks correct. What type of html element is "Color?" If it's just an html element, make sure that you have both id and name attributes on it.


Need Your Help

Unable to create object context

c# .net asp.net-mvc entity-framework

I'm getting the Unable to create object context error when using Entity framework in ASP.NET MVC.