5

I have a search page that has 6 textboxes which i pass as FormCollection to the action in the controller. I dont want to search for records if ther is no values in textboxes.

Is there a way to loop through all textboxes in FormCollection to check which ones have values in them?

I am a student in the college and this project is part of my summer experience program. I realize that this is a newbie question :) Thank you!

Alex
  • 608
  • 4
  • 11
  • 25
  • A full answer with multiple methods can be found [here](http://stackoverflow.com/questions/762825/how-can-a-formcollection-be-enumerated-in-asp-net-mvc). – Rhys Stephens Dec 14 '15 at 01:27

2 Answers2

12

You can loop through the FormCollection like this:

foreach( string key in forms.Keys )
{
    ...
}

However, note that the browser only sends you names and values. It does not send you the types of inputs, so you have no way to check if the value is a checkbox, unless you know all checkboxes names in advance. But if that's the case, you don't need to loop - just take them out of the collection by name.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
1
List<string> list = new List<string>();
for(int i= 0; i< form.AllKeys.Count(); ++i)
{
    list.Add(form.Get(i));
}

This will give you all the actual values for each key

Jonathan
  • 3
  • 2