Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC Drop Down List not mapping to Model
    primarykey
    data
    text
    <p>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. </p> <pre><code>public class Patient { public int ConsultantId {get;set;} } </code></pre> <p>I then setup an create and edit page and use the HTML.DropDownListFor Helper to produce a list of possible consultants </p> <pre><code> @Html.DropDownListFor(model =&gt; model.ConsultantId, ((IEnumerable&lt;Web.Models.Consultant&gt;)ViewBag.PossibleConsultants).Select(option =&gt; new SelectListItem { Text = Html.DisplayTextFor(_ =&gt; option.ConsultantName).ToString(), Value = option.ConsultantId.ToString(), Selected = (Model != null) &amp;&amp; (option.ConsultantId == Model.ConsultantId) }), "Choose...") </code></pre> <p>Which works fine, but I now want to move to having the Consultant object on the patient class e.g.</p> <pre><code> public class Patient { public virtual Consultant Consultant {get;set;} } public class Consultant { public virtual ICollection&lt;Patient&gt; Patient {get;set;} } </code></pre> <p>I now try to setup the view using the DropDownListfor but this time on the model.Consultant e.g.</p> <pre><code> @Html.DropDownListFor(model =&gt; model.Consultant, ((IEnumerable&lt;Web.Models.Consultant&gt;)ViewBag.PossibleConsultants).Select(option =&gt; new SelectListItem { Text = Html.DisplayTextFor(_ =&gt; option.ConsultantName).ToString(), Value = option.ConsultantId.ToString(), Selected = (Model != null) &amp;&amp; (option.ConsultantId == Model.Consultant.ConsultantId) }), "Choose...") </code></pre> <p>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<br> '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. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload