I am trying to develop an application in MVC 3 using EF codefirst. When I use int properties and convention to configure foreign key relationships, for example.
public class Patient { public int ConsultantId {get;set;} }
Then I set up the create and edit page and use the HTML.DropDownListFor Helper to create a list of potential 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 well, but now I want to move on to the fact that the consultant object is on the patientβs class, for example,
public class Patient { public virtual Consultant Consultant {get;set;} } public class Consultant { public virtual ICollection<Patient> Patient {get;set;} }
Now I'm trying to customize the view using 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...")
Create and edit the page correctly, and the consultant is correctly selected on the edit page, but when I submit the page, ModelState InValid to this error "Unable to convert" System.String "to print" Web.Models.Consultant. "Does anyone know how use DropDownList so that the model can be displayed back to the object.