Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

How do I do this using AutoMapper?

like image 487
chobo2 Avatar asked Feb 01 '11 18:02

chobo2


1 Answers

If we suppose that you have a model:

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

you could then 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've got your IEnumerable<FooModel> you would simply convert it to an IEnumerable<SelectListItem>:

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

A more realistic example would be to have the following view model:

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

So now your controller action could 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 strongly typed view:

@Html.DropDownListFor(
    x => x.SelectedItemId, 
    new SelectList(Model.Items, "Value", "Text")
)
like image 157
Darin Dimitrov Avatar answered Nov 14 '22 20:11

Darin Dimitrov