How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")
You can get all keys in the Request.Form and then compare and get your desired values.
Your method body will look like this: -
List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("List"))
{
listValues.Add(Convert.ToInt32(Request.Form[key]));
}
}
Waqas Raja's answer with some LINQ lambda fun:
List<int> listValues = new List<int>();
Request.Form.AllKeys
.Where(n => n.StartsWith("List"))
.ToList()
.ForEach(x => listValues.Add(int.Parse(Request.Form[x])));
Here is a way to do it without adding an ID to the form elements.
<form method="post">
...
<select name="List">
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
<select name="List">
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
...
</form>
public ActionResult OrderProcessor()
{
string[] ids = Request.Form.GetValues("List");
}
Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:
public class OrderModel
{
public string[] List { get; set; }
}
public ActionResult OrderProcessor(OrderModel model)
{
string[] ids = model.List;
}
Hope this helps.