Search code examples
c#asp.net-mvcformcollection

Extract Key Value Pairs from a named Collection MVC


I am pulling form values from a loosely bound razor form. The reason I am not using strongly bound model is that the payment value fields and categories are dynamic.

The form collection array reaching the controller is as below:

Payment {"1":"120","4":"23","6":"12","8":"120","9":"100"}

I need to split the array like (When PayCatId =1, Pay =120) (When PayCatId =4, Pay=23) etc..

string [] pa =collection["Payment"].Split(char.Parse(","));
string [] pc =collection.AllKeys["Payment"].Split(char.Parse(","));

Then I am trying to save to database using the logic below;

for (var i = 0; i < pa.Length; i++)
{
    payment.Pay = Convert.ToDecimal(pa[i]);                 
    payment.PayCatId = Convert.ToInt32(pa[i]);  (added:how do i get this value from pair?)
    payment.PayDate = DateTime.Now;
    db.Payments.Add(payment);
    db.SaveChanges();
 }

Removed the Error bit as I have been enlightened that that approach is not applicable I also want to know if this is the right and reliable approach to achieve this objective.


Solution

  • Just loop through two steps at a time instead of one

    for (var i = 0; i < pa.Length; i+=2)
    {
        payment.Pay = Convert.ToDecimal(pa[i]);                 
        payment.PayCatId = Convert.ToInt32(pa[i+1]);
        payment.PayDate = DateTime.Now;
        db.Payments.Add(payment);
        db.SaveChanges();
     }