4

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Richard Forrest
  • 3,567
  • 2
  • 23
  • 32

2 Answers2

2

I've found a solution that works for me. Using entitiy framework codefirst you can have both the public int ConsultantId property and the public virtual Consultant property in the same class. There is still only one relationship in the database which is defined by the ConsultantId property. So if this is a nullable int the relationship would be optional.

Richard Forrest
  • 3,567
  • 2
  • 23
  • 32
  • Is this really the best approach? Has anyone come across a way to do this without having to declare a separate ID property? –  Dec 28 '12 at 09:39
1

The dropdown list select value (ConsultantId) is being bound the the Consultant property on the model, which is of type Consultant.

Could you bind dropdown value to Consultant.ConsultantId instead?

Example:

@Html.DropDownListFor(model => model.Consultant.ConsultantId, // the rest of the statement goes here...
John Allers
  • 3,052
  • 2
  • 30
  • 36