简体   繁体   中英

Enumerating posted data in form order in ASP.NET MVC

Order entry form from Windows CE 6 contains fields with duplicate column names. This data needs to be enumerated in ASP.NET MVC4 application in post controller.

Column names are not known in the controller, since the form is created at runtime from user-defined data.

I tried code below, but it returns comma separated values for duplicate names.

How to get every posted key/value pair separately in the order which they appear in the form? Data can also be posted in json format using jquery, if that can solve the issue.

Observed result:

id=1,1,2
orderdate=2013-01-01
quantity=12.2,15

Expected result:

  id=1
  orderdate=2013-01-01
  id=1
  quantity=12.2
  id=2
  quantity=15

View:

<!DOCTYPE html>
<html>
<body>
<form method='post' action='SaveOrder'>

Order id<input name='id' type='text' value='1' />
Date <input name='orderdate' type='date' value='2013-01-01'/>

Row 1 id <input name='id' type='text' value='1' />
Quantity <input name='quantity' type='text' value='12.2'/>

Row 2 id <input name='id' type='text' value='2'/>
Quantity <input name='quantity' type='text' value='15' />

<input type='submit' value='Save order'/>    
</form>
</body></html>

Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveOrder(NameValueCollection form) 
{
    for (int i = 0; i < form.Count; i++)
        Console.WriteLine(form.GetKey(i)+"="+ form[i].ToString());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveOrder()
{
    foreach (string key in Request.Form.AllKeys)
    {
        foreach (string value in Request.Form.GetValues(key))
        {
            Debug.WriteLine("{0} = {1}", key, value);
        }
    }
    return View();
}

Output:

id = 1
id = 1
id = 2
orderdate = 2013-01-01
quantity = 12.2
quantity = 15

The only thing left for you to do is to reorder the parameters to

id = 1
orderdate = 2013-01-01
id = 1
quantity = 12.2
quantity = 15
id = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM