0

I have a "list" view which is basically receiving a model of type IEnumerable(Thing). I have no control over Thing; it is external.

That's been nearly fine. One of the properties of 'Thing' is an enum of flags. I'd like to improve the formatting of this property in the view. I have read some strategies for that. My plan was to create a ViewModel that knows better about formatting.

I'd like to know if there's a direct way to create an IEnumerable(ViewThing) from IEnumerable(Thing).

An obvious way would be to iterate through the IEnumerable of Things where for each Thing I would create a ViewThing and stuff it with the Thing's data, resulting in an IEnumerable of ViewThings.

But backing up, I'm also interested in smarter ways to handle formatting the flags for viewing.

Community
  • 1
  • 1
Joel Skrepnek
  • 1,651
  • 1
  • 13
  • 21

1 Answers1

1

You could use AutoMapper to map between your domain models and view models. The idea is that you define a mapping between Thing and ThingViewModel and then AutoMapper will take care of mapping collections of those objects so that you don't have to iterate:

public ActionResult Foo()
{
    IEnumerable<Thing> things = ... get the things from whererver you are getting them
    IEnumerable<ThingViewModel> thingViewModels = Mapper.Map<IEnumerable<Thing>, IEnumerable<ThingViewModel>>(things);
    return View(thingViewModels);
}

Now all that's left is define the mapping between a Thing and ThingViewModel:

Mapper
    .CreateMap<Thing, ThingViewModel>().
    .ForMember(
        dest => dest.SomeProperty,
        opt => opt.MapFrom(src => ... map from the enum property)
    )
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks. I'm wondering where the logical place to define the mapping would be? It's likely only to used in one place, in one controller. – Joel Skrepnek Jul 03 '12 at 21:29
  • If you use AutoMapper, the mapping (`CreateMap`) should be defined only once for the entire lifetime of the application, so ideally this should be a method called from `Application_Start`. If you don't want to use AutoMapper to have a mapping layer between your domain models and view models, then the controller action might be a good place to put this mapping logic. – Darin Dimitrov Jul 03 '12 at 21:35