How to map List in SelectList in ASP.NET MVC using AutoMapper?

I have a list of data that I want to bind to a SelectList element in my ViewModel.

How to do this using AutoMapper ?

+6
c # asp.net-mvc automapper
source share
1 answer

If we assume that you have a model:

public class FooModel { public int ModelId { get; set; } public string Description { get; set; } } 

you could have a mapping between FooModel and 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) ); 

and then when you have IEnumerable<FooModel> , you simply convert it to IEnumerable<SelectListItem> :

 IEnumerable<FooModel> models = ... IEnumerable<SelectListItem> viewModels = Mapper .Map<IEnumerable<FooModel>, IEnumerable<SelectListItem>>(models); 

A more realistic example would be the following presentation model:

 public class MyViewModel { public string SelectedItemId { get; set; } public IEnumerable<SelectListItem> Items { get; set; } } 

So, now your controller action might look like this:

 public ActionResult Index() { IEnumerable<FooModel> items = ... var viewModel = new MyViewModel { Items = Mapper.Map<IEnumerable<FooModel>, IEnumerable<SelectListItem>>(items) }; return View(viewModel); } 

and inside your strictly typed view:

 @Html.DropDownListFor( x => x.SelectedItemId, new SelectList(Model.Items, "Value", "Text") ) 
+15
source share

All Articles