Asp.net mvc3: How to pull data from a database and populate the view model for one purpose?

I need to pull data from a database and populate a view model, is there a better way to do this? I am currently doing something like this.

ViewModel vm = new ViewModel(); var recentBill = context.Money.Take(10); foreach (var r in recnetBill) { vm.lst.Add(r); } 
+4
source share
3 answers

Assuming your ViewModel looks like this:

 public class ViewModel { IEnumerable<Money> lst { get; set; } // other properties } 

Just do the following:

 public ActionResult GetMonies() { var monies = context.Money .Take(10) .ToList(); var model = new ViewModel { lst = monies }; return View(model); } 
0
source

IEnumerable has a ToList() function that returns a list of the specified type.

 vm.lst = context.Money.Take(10).ToList(); // returns a List<Money> 
+2
source

I would recommend that you prevent the possibility of changing ViewModel.lst, that is, the lst type should be IEnumerable instead of List / IList (of course, if your additional code does not require a list function).

Also, I suppose you are not modifying the lst link, so you can remove setter and initialize lst through the constructor.

  public class ViewModel { public ViewModel(IEnumerable<Money> lst) { this._lst = lst; } private readonly IEnumerable<Money> _lst; IEnumerable<Money> Lst { get { return this._lst; } } // other properties } public ActionResult GetMonies() { var model = new ViewModel(context.Money.Take(10).ToArray()); return View(model); } 

This approach ensures that consumers of your code will not modify your ViewModel.Lst by accident.

+1
source

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


All Articles