Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC3 dropdown list that displays mutliple properties per item
    text
    copied!<p>I want to have a dropdownlist in my view that displays a patient's ID, First Name, and Last Name. With the code below, it displays each patient's First Name. How can I pass all three properties into the viewbag and have them display in the dropdownlist?</p> <p>Controller</p> <pre><code>public ActionResult Create() {ViewBag.Patient_ID = new SelectList(db.Patients, "Patient_ID", "First_Name"); return View(); } </code></pre> <p>View</p> <pre><code> &lt;div class="editor-field"&gt; @Html.DropDownList("Patient_ID", String.Empty) @Html.ValidationMessageFor(model =&gt; model.Patient_ID) &lt;/div&gt; </code></pre> <p>Thanks.</p> <p>Ok, I have edited my code as follows, and I receive the error "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedPatientId'."</p> <pre><code>Controller public ActionResult Create() { var model = new MyViewModel(); { var Patients = db.Patients.ToList().Select(p =&gt; new SelectListItem { Value = p.Patient_ID.ToString(), Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name) }); var Prescribers = db.Prescribers.ToList().Select(p =&gt; new SelectListItem { Value = p.DEA_Number.ToString(), Text = string.Format("{0}-{1}-{2}", p.DEA_Number, p.First_Name, p.Last_Name) }); var Drugs = db.Drugs.ToList().Select(p =&gt; new SelectListItem { Value = p.NDC.ToString(), Text = string.Format("{0}-{1}-{2}", p.NDC, p.Name, p.Price) }); }; return View(model); } </code></pre> <blockquote> <p>View Model</p> </blockquote> <pre><code> public class MyViewModel { [Required] public int? SelectedPatientId { get; set; } public IEnumerable&lt;SelectListItem&gt; Patients { get; set; } [Required] public int? SelectedPrescriber { get; set; } public IEnumerable&lt;SelectListItem&gt; Prescribers { get; set; } [Required] public int? SelectedDrug { get; set; } public IEnumerable&lt;SelectListItem&gt; Drugs { get; set; } } </code></pre> <p>View</p> <pre><code>@using (Html.BeginForm()) { @Html.ValidationSummary(true) @Html.DropDownListFor( x =&gt; x.SelectedPatientId, Model.Patients, "-- Select patient ---" ) @Html.ValidationMessageFor(x =&gt; x.SelectedPatientId) &lt;button type="submit"&gt;OK&lt;/button&gt; @Html.DropDownListFor( x =&gt; x.SelectedPrescriber, Model.Patients, "-- Select prescriber ---" ) @Html.ValidationMessageFor(x =&gt; x.SelectedPrescriber) &lt;button type="submit"&gt;OK&lt;/button&gt; } </code></pre>
 

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