I'm trying to develop an application in MVC 3 using EF codefirst. When I use int properties and convention to set up foreign key relationships e.g.
public class Patient
{
public int ConsultantId {get;set;}
}
I then setup an create and edit page and use the HTML.DropDownListFor Helper to produce a 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, but I now want to move to having the Consultant object on the patient class e.g.
public class Patient
{
public virtual Consultant Consultant {get;set;}
}
public class Consultant {
public virtual ICollection<Patient> Patient {get;set;}
}
I now try to setup the view using the DropDownListfor but this time on the 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 and edit page load correctly and the consultant is correctly selected on the edit page but when I post the page the ModelState is InValid on this error "Can't convert
'System.String' to type 'Web.Models.Consultant". Does anyone know how to use the DropDownListFor so the Model can be mapped back to an object.