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

Las*_*eak 22 c# asp.net asp.net-mvc httpwebrequest asp.net-mvc-2

目前使用下面的代码创建一个字符串数组(元素),其中包含来自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<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);
Run Code Online (Sandbox Code Playgroud)

Waq*_*aja 37

您可以获取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]));
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 14

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])));
Run Code Online (Sandbox Code Playgroud)


ali*_*ray 8

这是一种在不向表单元素添加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");
}
Run Code Online (Sandbox Code Playgroud)

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

public class OrderModel
{
    public string[] List { get; set; }
}

public ActionResult OrderProcessor(OrderModel model)
{
    string[] ids = model.List;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.