I'd like to know the best way of converting a list of domain object I retrieve into custom ViewModels in the controller
e.g.
IList<Balls> _balls = _ballsService.GetBalls(searchCriteria);
into
IList<BallViewModels> _balls = _ballsService.GetBalls(searchCriteria);
it doesn't have to be exactly as I've outlined above i.e. it doesn't have to be an IList and if not accessing the service directly and instead go thru some other layer that converts the objects to viewmodels then that is ok too.
thanks
For simple objects you could just use Linq:
IList<BallViewModel> _balls = _ballsService.GetBalls(searchCriteria)
.Select(b => new BallsViewModel
{
ID = b.ID,
Name = b.Name,
// etc
})
.ToList();
That can get pretty repetitive though, so you may want to give your BallViewModel class a constructor that accepts a Ball and does the work for you.
Another approach is to use a library like AutoMapper to copy the properties (even the nested ones) from your domain object to your view model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With