kurasa
kurasa

Reputation: 5323

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

Upvotes: 5

Views: 5712

Answers (3)

Ragesh
Ragesh

Reputation: 3073

I use AutoMapper to do this all the time. It's really flexible and has worked for me without any troubles so far.

First you set up a map like during your app's initialization:

Mapper.CreateMapping<Balls, BallViewModel>();

And whenever you need to map the objects, you would do this:

Mapper.Map<IList<Balls>, IList<BallViewModel>>(_ballsService.GetBalls());

Like I said, it's very flexible and you can modify how the mapping happens for each property using a fluent API.

Upvotes: 1

Murph
Murph

Reputation: 10190

Probably a bit of Linq, something along the lines of

var ballQuery = from ball in _ballsService.GetBalls(searchCriteria)
                select new BallViewModels
                {
                    Diameter = ball.Diameter,
                    color = ball.Color,
                    ...
                }
IList<BallViewModels> _balls = ballQuery.ToList();

Either that or the question is more complicated than I think...

Upvotes: 1

Matt Hamilton
Matt Hamilton

Reputation: 204239

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.

Upvotes: 8

Related Questions