问题描述
|
当前使用以下代码创建包含所有内容的字符串数组(元素)
来自Request.Form.GetValues(\“ ElementIdName \”)的字符串值,问题在于
要使用此功能,我视图中的所有下拉列表必须具有相同的元素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<int> pidlist = new List<int>();
//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<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对LINQ lambda的回答:
List<int> listValues = new List<int>();
Request.Form.AllKeys
.Where(n => n.StartsWith(\"List\"))
.ToList()
.ForEach(x => listValues.Add(int.Parse(Request.Form[x])));
, 这是一种无需在表单元素上添加ID的方法。
<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\");
}
然后,id将包含从选择列表中选择的所有选项值。另外,您可以沿着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方法也有效。