我希望在我的視圖中有一個顯示患者ID,名字和姓氏的下拉列表。使用下面的代碼,它會顯示每個患者的名字。我如何將所有三個屬性都傳遞到viewbag中並讓它們顯示在下拉列表中?MVC3下拉列表,顯示每個項目的多個屬性
控制器
public ActionResult Create()
{ViewBag.Patient_ID = new SelectList(db.Patients, "Patient_ID", "First_Name");
return View();
}
查看
<div class="editor-field">
@Html.DropDownList("Patient_ID", String.Empty)
@Html.ValidationMessageFor(model => model.Patient_ID)
</div>
感謝。
好的,我編輯了我的代碼,如下所示,並且收到錯誤消息「沒有ViewData項的類型爲」IEnumerable「,其中包含」SelectedPatientId「鍵。
Controller
public ActionResult Create()
{
var model = new MyViewModel();
{
var Patients = db.Patients.ToList().Select(p => 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 => 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 => new SelectListItem
{
Value = p.NDC.ToString(),
Text = string.Format("{0}-{1}-{2}", p.NDC, p.Name, p.Price)
});
};
return View(model);
}
視圖模型
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
[Required]
public int? SelectedPrescriber { get; set; }
public IEnumerable<SelectListItem> Prescribers { get; set; }
[Required]
public int? SelectedDrug { get; set; }
public IEnumerable<SelectListItem> Drugs { get; set; }
}
查看
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
@Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
@Html.DropDownListFor(
x => x.SelectedPrescriber,
Model.Patients,
"-- Select prescriber ---"
)
@Html.ValidationMessageFor(x => x.SelectedPrescriber)
<button type="submit">OK</button>
}
Tha噸錯誤通常意味着您的項目列表爲空 –