Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC4 - Pass List to view via view model

I have a model Person (with among other fields the day of Birth) and I want to pass a list of all persons, together with the calculated age of each person, to the view

Therefor:

  1. The view model

    public class vm_PersonList
    {
        public Person Person { get; set; } 
        public int age { get; set; }
    }
    
  2. The controller action:

    public ActionResult PersonList()
    {
        ViewBag.Message = "My List";
    
        var list = new List<vm_PersonList>();
        var list_p = new vm_PersonList();
    
    
        foreach (var p in db.Person)
        {
            list_p.Person = p;
            //the age will be calculated based on p.birthDay, not relevant for the    
            //current question
            list_p.age = 23;
    
            list.Add(list_p);
        }
        return View(list);
    }
    
  3. The view

    @model List<programname.Viewmodels.vm_PersonList>
    
    @foreach (var p in Model)
    {
        <tr>
            <td>
                @p.Person.FullName
            </td>
            <td>
                @p.age
            </td>  
        </tr>
    }
    

The Person table contains for example 6 entries. When debugging the application I see:

At the end of the controller action "list" contains correctly the 6 different Person entries

In the view, the "Model" contains 6 entries, but 6 times the last "database entry". Does anyone have a suggestion to solve this issue?

like image 902
user1416778 Avatar asked Feb 21 '23 08:02

user1416778


1 Answers

You are using the same list_p instance over and over again inside the loop. So you are constantly updating its Person property. And since Person is a reference type you are modifying the same reference in memory. At the last iteration of the loop you are obviously replacing this reference with the last instance of Person which explains why you are seeing the same person in the view.

Try like this, seems lot easier:

public ActionResult PersonList()
{
    ViewBag.Message = "My List";
    var model = db.Person.Select(p => new vm_PersonList
    {
        Person = p,
        age = 23
    }).ToList();
    return View(model);
}
like image 92
Darin Dimitrov Avatar answered Mar 03 '23 14:03

Darin Dimitrov