ASP MVC4 - Skip List to View Through View Model

I have a Person model (with other birthday fields) and I want to transfer a list of all persons along with the calculated age of each person to the presentation

Therefor:

  • Presentation model

    public class vm_PersonList { public Person Person { get; set; } public int age { get; set; } } 
  • 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); } 
  • View

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

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

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

In the view, the "Model" contains 6 records, but 6 times the last "record in the database." Anyone have a suggestion to solve this problem?

+4
source share
3 answers

You use the same instance of list_p over and over inside the loop. This way you are constantly updating the Person property. And since Person is a reference type, you are changing the same link in memory. At the last iteration of the loop, you obviously replace this link with the last instance of Person, which explains why you see the same person in the view.

Try this, it seems a 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); } 
+7
source

You are working on the same instance of vm_PersonList. Move vm_PersonList instance to loop

 foreach (var p in db.Person) { var list_p = new vm_PersonList(); 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); } 
+1
source

This is a problem with the size of your list_p instance. Try changing the controller code to:

 public ActionResult PersonList() { ViewBag.Message = "My List"; var list = db.Person .Select(p => new vm_PersonList { Person = p, age = 23, }) .ToList(); return View(list); } 
0
source

Source: https://habr.com/ru/post/1414316/


All Articles