Search code examples
c#asp.net-mvclistforeachdropdownbox

ASP.NET - Foreach last element appears on whole list


This just drives me nuts. After populating list with cont records it changes so every value is the same. The value is the one from the last record.

public ActionResult Index()
{
    var cont = db.AspNetUsers.ToList();
    var list = new List<SelectListItem> ();
    SelectListItem ctr = new SelectListItem();

    foreach (var item in cont)
    {
        ctr.Text = item.Email;
        ctr.Value = item.Email;
        list.Add(ctr);

        //last iteration everything is fine, every element of list holds
        //another value
    }       

   // debugger shows that all list elements have the same text and value
   TempData["list"] = list;

   return View();
}

Thanks!


Solution

  • That is because you are adding and editing the same object ctr each iteration. It is a reference type so every time you do ctr.*something* without initializing a new object for ctr to reference too, you will be editing the same one.

    foreach (var item in cont)
    {
        SelectListItem ctr = new SelectListItem();
        ctr.Text = item.Email;
        ctr.Value = item.Email;
        list.Add(ctr);
    }
    

    Move SelectListItem ctr = new SelectListItem(); into the list