2

I've watched this video a couple of times and really like the custom ActionResult that he creates that handles mapping your source object to your destination object. My problem is a lot of the time my ViewModel's will have a collection property that will be shown as a DropDownList or Listbox in my view but is not available in the source object. Therefore I call another service to retrieve the collection of source objects and then map this to the VeiwModel's property.

Example:

LetterEditModel editModel = _mappingEngine.Map<Letter, LetterEditModel>(_letterRepository.GetLetter(1));
editModel.Departments = _mappingEngine.Map<Department[], SelectOptionModel[]>(_departmentRepository.GetAllDepartments());

Since Departments are not a property of the Letter object, I must make another query in order to retrieve my options for the DropDownList. This requires another AutoMapper call in order to populate the ViewModel property.

I found the google group for AutoMapper in which Jimmy kind of explains some approaches to this.

Jimmy Bogard's comments on this:

We have a few ways of doing this, depending on how the select list varies. If it's a hard list of items, then often there's some model behind it (like State or Country), so our view model just has that one type and our editor templates takes care of actually pulling the list of states.

If it varies based on some parameter, we have to pass the actual select list down, and basically do a Mapper.Map + post-map manipulation (not in AutoMapper) to fill in the pieces. We use AutoMapper to fill in the major pieces, and the details w/ something else.

Finally, we might have something like a select list provider-type approach in our view:

Html.InputFor(m => m.UserRoles, opt => opt.SelectListProvider());

HTH,

Jimmy

I'm guessing that the EditorFor template would be using the DependencyResolver in order to get the correct service in order to query for your collection that you can generate your DropDownList or ListBox for. I don't know if that code belongs in a server-side code block in the EditorFor template. Something about this just doesn't seem right to me but I could be completely wrong. I always felt that any data access calls would be done in the body of the action and not from a view.

I'm not really sure what he means by his second and third recommendations.

I have to believe someone has solved this problem and has an elegant solution for this. Any recommendations or ideas would be greatly appreciated.

4

0 回答 0