MVC dropdown not displaying model

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.

+4
source share
2 answers

I found a solution that works for me. Using the enitiy framework codefirst, you can have both the public property int ConsultantId and the public virtual property of the Consultant in one class. There is still only one relationship in the database, which is determined by the ConsultantId property. Therefore, if it is a value with a null int value, this will be optional.

+2
source

The selected value of the drop-down list (ConsultantId) binds the property of the Consultant to a model that has the type Consultant.

Could you associate a dropdown with a consultant. Instead of this? Instead of this?

Example:

 @Html.DropDownListFor(model => model.Consultant.ConsultantId, // the rest of the statement goes here... 
+1
source

Source: https://habr.com/ru/post/1340334/


All Articles