我希望在我的 View 中有一个下拉列表,显示患者的 ID、名字和姓氏。使用下面的代码,它会显示每个患者的名字。如何将所有三个属性传递到 View 袋中并让它们显示在下拉列表中?
Controller
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>
谢谢。
好的,我已按如下方式编辑了代码,但收到错误“不存在具有键“SelectedPatientId”的“IEnumerable”类型的 ViewData 项。”
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);
}
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>
}
最佳答案
我建议您根本不要使用任何ViewBag
并定义 View 模型:
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
}
然后让您的 Controller 操作填充并将此 View 模型传递给 View :
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);
}
最后在强类型 View 中显示下拉列表:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
@Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
}
关于asp.net-mvc-3 - MVC3 下拉列表显示每个项目的多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8370498/