Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a list of domain objects to viewmodels on the Controller in ASP.NET MVC

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

like image 935
kurasa Avatar asked Nov 08 '09 23:11

kurasa


1 Answers

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.

like image 109
Matt Hamilton Avatar answered Nov 15 '22 00:11

Matt Hamilton