我有一个数据列表,我想绑定到我的viewmodel中的SelectList.
如何使用AutoMapper执行此操作?
@R_301_323@
如果我们假设你有一个模型:
public class FooModel { public int ModelId { get; set; } public string Description { get; set; } }
然后你可以在FooModel和SelectListItem之间建立一个映射:
Mapper .CreateMap<FooModel,SelectListItem>() .ForMember( dest => dest.Value,opt => opt.MapFrom(src => src.ModelId.ToString()) ) .ForMember( dest => dest.Text,opt => opt.MapFrom(src => src.Description) );
然后当你获得IEnumerable< FooModel>你只需将它转换为IEnumerable< SelectListItem>:
IEnumerable<FooModel> models = ... IEnumerable<SelectListItem> viewmodels = Mapper .Map<IEnumerable<FooModel>,IEnumerable<SelectListItem>>(models);
更现实的例子是拥有以下视图模型:
public class Myviewmodel { public string SelectedItemId { get; set; } public IEnumerable<SelectListItem> Items { get; set; } }
所以现在你的控制器动作可能如下所示:
public ActionResult Index() { IEnumerable<FooModel> items = ... var viewmodel = new Myviewmodel { Items = Mapper.Map<IEnumerable<FooModel>,IEnumerable<SelectListItem>>(items) }; return View(viewmodel); }
在强类型视图中:
@Html.DropDownListFor( x => x.SelectedItemId,new SelectList(Model.Items,"Value","Text") )