简体   繁体   中英

list not populating in c#

I have a view in MVC and on regeneration of form i am populating a list using forms collection. but the list is not populating correctly and i am sure i am missing something in the list. kindly check my code

    int noOfRows=Request.Form["rows"].ConvertToInt()};
    int noOfColmn=Request.Form["colmns"].ConvertToInt()};

    List<mymodel> list1= new List<mymodel>();


                  for (int roww = 1; roww < noOfRows; roww++)
                   {
                         list1=new List<mymodel>
                         {
                             new mymodel
    {
name=Request.Form["name-" + roww + ""].ConvertToInt() ,
rollno= Request.Form["rollno-" + roww + ""].ConvertToInt(),
                                 subjs=new List<mymodel>()}
                         };



     for (var colmn = 1; colmn < noOfColmn; colmn++)
                        {
                        var subjs= new List<mymodel> 
                        { new mymodel
                        {subjs=Request.Form["subj-" + roww + "-" + colmn + ""].ConvertToInt()}
                        };

                        }
                   }

                  ViewBag._list1 = list1;

You should initialize the list1 variable only outside the for loop and add elements to the same list when inside the loop.
Your current code reinitializes this list1 variable at every loop. The internal loop does the same thing with the property subjs that appears to be another List<mymodel> .

I propose this code.
Of course, I am not able to test it, so let me know if this pseudocode fits your requirements.

int noOfRows=Request.Form["rows"].ConvertToInt()};
int noOfColmn=Request.Form["colmns"].ConvertToInt()};

// Create the list1 just one time here.
List<mymodel> list1= new List<mymodel>();
for (int roww = 1; roww < noOfRows; roww++)
{
     // creates an instance of mymodel
     mymodel m = new mymodel
     {
         name=Request.Form["name-" + roww + ""].ConvertToInt() ,
         rollno= Request.Form["rollno-" + roww + ""].ConvertToInt(),

         // create the internal list of mymodel
         subjs=new List<mymodel>()}
     };

     // add the model m to the list1 
     list1.Add(m);

     // loop to create the internal models
     for (var colmn = 1; colmn < noOfColmn; colmn++)
     {
          mymodel m2 = new mymodel
          {
               subjs=Request.Form["subj-" + roww + "-" + colmn + ""].ConvertToInt()}
          };

          // add all the subsequent models to the sublist internal to the first model
          m.subjs.Add(m2);
     }
}
ViewBag._list1 = list1;

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