7

In my ASP.NET MVC 2 (RC) project - I'm using AutoMapper to map between a Linq to Sql class (Media) and a view model (MediaVM). The view model has a SelectList property for a drop down in the view. I have a custom value resolver to populate the SelectList property items from the db, but am wondering if there's a way to pass a couple values from the source model into the resolver (using ConstructedBy method?) to a) define the selected item and b) filter the items from the db. The source object gets passed into the custom resolver - but the resolver is used on several different view models with different types of source objects, so would rather define where to get the values from in my mapping config. Here is my view model:

public class MediaVM
{
    public bool Active { get; set; }
    public string Name { get; set; }

    [UIHint("DropDownList")]
    [DisplayName("Users")]
    public SelectList slUsers { get; private set; }
}        

The automapper mapping config:

    Mapper.CreateMap<Media, MediaVM>()
        .ForMember(dest => dest.slUsers, opt => opt.ResolveUsing<UsersSelectListResolver>());

It would be nice to be able to do something like this on the .ForMember mapping clause:

.ConstructedBy(src => new UsersSelectListResolver(src.UserID, src.FilterVal))

Is there a way to accomplish this?

1
  • Bryan, how do you populate SelectList from DB?
    – awaisj
    Commented Nov 17, 2011 at 11:44

2 Answers 2

8

I like that idea as a feature request. You can do something like that right now, with MapFrom:

ForMember(dest => dest.slUsers, opt => opt.MapFrom(src => new UsersSelectListResolver(src).Resolve(src));
1
  • thanks jimmy! was hoping you'd chime in and confirm i wasn't missing something obvious.
    – Bryan
    Commented Jan 17, 2010 at 20:36
2

I found your posting trying to do the same thing. I decided on a simple approach and skip trying to map to my select list directly via AutoMaper. I simply return an array into my ViewModel and reference that object for my select list. The array gets mapped, select list object does not. Simple, effective. And, IMHO each is doing it's intended task - the mapper maps, the ViewModel does the layout

View Model code:
        [DisplayName("Criterion Type")]
        public virtual CriterionType[] CriterionTypes { get; set; }

        [DisplayName("Criterion Type")]
        public SelectList CriterionTypeList
        {
            get
            {
                return new SelectList(CriterionTypes, "Id", "Key");
            }
        }  

my mapper:

 Mapper.CreateMap<Criterion, CriterionForm>()
            .ForMember(dest => dest.CriterionTypeList, opt => opt.Ignore());     
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.