I have a List of data that I want to bind to a SelectList in my ViewModel.
How do I do this using AutoMapper?
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")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With