我希望在我的视图中有一个下拉列表,显示患者的ID,名字和姓氏。使用下面的代码,它显示每个患者的名字。如何将所有三个属性传递到viewbag并将它们显示在下拉列表中?
控制器
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>
感谢。
好的,我已经按如下方式编辑了我的代码,并且收到错误“没有类型'IEnumerable'的ViewData项具有'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>
}
答案 0 :(得分:1)
我建议您不要使用任何ViewBag
并定义视图模型:
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
}
然后让控制器操作填充并将此视图模型传递给视图:
public ActionResult Create()
{
var model = new MyViewModel
{
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)
});
};
return View(model);
}
最后在强类型视图中显示下拉列表:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
@Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
}
答案 1 :(得分:1)
实现这一目标的简单方法是通过修改模型类或添加/修改部分类来创建模型的附加属性
[NotMapped]
public string DisplayFormat
{
get
{
return string.Format("{0}-{1}-{2}", Patient_ID, First_Name, Last_Name);
}
}