c# - Automapper - Convert string property to SelectList? -
i'm starting learn automapper in mvc project. have base entity "attendee" string field gender (possible values of "m" or "f").
i have basic mapping created between attendee , attendeeeditview objects. want convert "m" or "f" gender string on model side selectlist on viewmodel side, appropriate value selected in list.
i think need valueresolver this... here's i've written:
public class gendermenuresolver : valueresolver<attendee, selectlist> { protected override selectlist resolvecore( attendee source ) { list<object> items = new list<object>(){ new{ value = "f" , text = "female" }, new{ value = "m" , text = "male" } }; string gender = source.gender ?? ""; string selectedvalue = new list<string>() { "m", "f" }.contains( gender.toupper() ) ? gender.toupper() : ""; selectlist gendermenu = new selectlist( items, "value", "text", selectedvalue ); return gendermenu; } }
and mapping code:
mapper.createmap<attendee, attendeeeditview>() .formember( dest => dest.gender, opt => opt.resolveusing<gendermenuresolver>() ); list<attendeeeditview> viewmodel = mapper.map<list<attendeeeditview>>( attendees );
stepping through can see code executes , outputs proper selectlist. however, following error:
mapping types: selectlist -> selectlist system.web.mvc.selectlist -> system.web.mvc.selectlist
destination path: list`1[0].gender.gender
source value: system.web.mvc.selectlist
first, ".gender.gender" mapping seems incorrect.
but appears root issue... inner exception message reveals this:
"type 'system.web.mvc.selectlist' not have default constructor"
can me identify i'm doing wrong, or perhaps better approach should using? thanks.
i think you're making more difficult needs be. not needs mapped, in fact things selectlist
s shouldn't mapped because they're relevant view model, not model.
so, in view model like:
public string gender { get; set; } public selectlist genderchoices { { return new selectlist(new list<selectlistitem> { new selectlistitem { value = "m", text = "male" }, new selectlistitem { value = "f", text = "female" } }, "value", "text", gender); } }
where gender
mapped, genderchoices
exist on view model.
then, in view:
@html.dropdownlistfor(m => m.gender, model.genderchoices)
Comments
Post a Comment