如何从Request.Form获取所有元素值,而无需使用.GetValues(“ElementIdName”)确切指定哪个元素值

目前使用以下代码创建一个字符串数组(元素),其中包含来自Request.Form.GetValues(“ElementIdName”)的所有字符串值,问题是为了使其工作,我的View中的所有下拉列表必须具有出于显而易见的原因,我不希望他们使用相同的元素ID名称。 所以我想知道是否有任何方法让我从Request.Form获取所有字符串值而不显式指定元素名称。 理想情况下,我只想获取所有下拉列表值,我在C#中不是太热,但是没有办法让所有元素ID以“List”+“**”开头,所以我可以命名我的列表List1 ,List2,List3等

谢谢..

[HttpPost] public ActionResult OrderProcessor() { string[] elements; elements = Request.Form.GetValues("List"); int[] pidarray = new int[elements.Length]; //Convert all string values in elements into int and assign to pidarray for (int x = 0; x < elements.Length; x++) { pidarray[x] = Convert.ToInt32(elements[x].ToString()); } //This is the other alternative, painful way which I don't want use. //int id1 = int.Parse(Request.Form["List1"]); //int id2 = int.Parse(Request.Form["List2"]); //List pidlist = new List(); //pidlist.Add(id1); //pidlist.Add(id2); var order = new Order(); foreach (var productId in pidarray) { var orderdetails = new OrderDetail(); orderdetails.ProductID = productId; order.OrderDetails.Add(orderdetails); order.OrderDate = DateTime.Now; } context.Orders.AddObject(order); context.SaveChanges(); return View(order); 

您可以获取Request.Form中的所有键,然后比较并获得所需的值。

你的方法体看起来像这样: –

 List listValues = new List(); foreach (string key in Request.Form.AllKeys) { if (key.StartsWith("List")) { listValues.Add(Convert.ToInt32(Request.Form[key])); } } 

Waqas Raja回答了一些LINQ lambda乐趣:

 List listValues = new List(); Request.Form.AllKeys .Where(n => n.StartsWith("List")) .ToList() .ForEach(x => listValues.Add(int.Parse(Request.Form[x]))); 

这是一种在不向表单元素添加ID的情况下执行此操作的方法。

 
... ...
public ActionResult OrderProcessor() { string[] ids = Request.Form.GetValues("List"); }

然后,ids将包含选择列表中的所有选定选项值。 此外,你可以像这样下去Model Binder路线:

 public class OrderModel { public string[] List { get; set; } } public ActionResult OrderProcessor(OrderModel model) { string[] ids = model.List; } 

希望这可以帮助。

Request.Form是一个NameValueCollection。 在NameValueCollection中,您可以找到GetAllValues()方法。

顺便说一下,LINQ方法也可以工作。