c# - MVC Drop Down List not mapping to Model -
i'm trying develop application in mvc 3 using ef codefirst. when use int properties , convention set foreign key relationships e.g.
public class patient { public int consultantid {get;set;} }
i setup create , edit page , use html.dropdownlistfor helper produce list of possible consultants
@html.dropdownlistfor(model => model.consultantid, ((ienumerable<web.models.consultant>)viewbag.possibleconsultants).select(option => new selectlistitem { text = html.displaytextfor(_ => option.consultantname).tostring(), value = option.consultantid.tostring(), selected = (model != null) && (option.consultantid == model.consultantid) }), "choose...")
which works fine, want move having consultant object on patient class e.g.
public class patient { public virtual consultant consultant {get;set;} } public class consultant { public virtual icollection<patient> patient {get;set;} }
i try setup view using dropdownlistfor time on model.consultant e.g.
@html.dropdownlistfor(model => model.consultant, ((ienumerable<web.models.consultant>)viewbag.possibleconsultants).select(option => new selectlistitem { text = html.displaytextfor(_ => option.consultantname).tostring(), value = option.consultantid.tostring(), selected = (model != null) && (option.consultantid == model.consultant.consultantid) }), "choose...")
the create , edit page load correctly , consultant correctly selected on edit page when post page modelstate invalid on error "can't convert
'system.string' type 'web.models.consultant". know how use dropdownlistfor model can mapped object.
i've found solution works me. using entitiy framework codefirst can have both public int consultantid property , public virtual consultant property in same class. there still 1 relationship in database defined consultantid property. if nullable int relationship optional.
Comments
Post a Comment