2012-07-03 64 views
0

我有一个“列表”视图,它基本上接收IEnumerable(Thing)类型的模型。我无法控制事物;它是外在的。从IEnumerable模型初始化IEnumerable ViewModels

这几乎没有问题。 'Thing'的一个属性是标志的枚举。我想在视图中改进此属性的格式。我有read some strategies。我的计划是创建一个更好地了解格式的ViewModel。

我想知道是否有直接的方式从IEnumerable(Thing)创建IEnumerable(ViewThing)。

一个显而易见的方法是遍历IEnumerable的东西,对于每个东西我会创建一个ViewThing并用Thing的数据填充它,产生一个IEnumerable的ViewThings。

但是备份,我也有兴趣更聪明的方式来处理格式化标志以供查看。

回答

1

您可以使用AutoMapper来映射您的域模型和视图模型。这个想法是,你定义ThingThingViewModel之间的映射,然后让你不必重复AutoMapper会照顾这些对象的映射集合:

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); 
} 

现在,所有剩下的就是定义之间的映射a ThingThingViewModel

Mapper 
    .CreateMap<Thing, ThingViewModel>(). 
    .ForMember(
     dest => dest.SomeProperty, 
     opt => opt.MapFrom(src => ... map from the enum property) 
    ) 
+0

谢谢。我想知道定义映射的合理位置在哪里?它可能只能用在一个地方,在一个控制器中。 –

+0

如果使用AutoMapper,映射('CreateMap')应该只在应用程序的整个生命周期中定义一次,所以理想情况下这应该是一个从'Application_Start'调用的方法。如果您不想使用AutoMapper在域模型和视图模型之间建立映射层,那么控制器操作可能是放置此映射逻辑的好地方。 –

+0

谢谢澄清。 –