ASP.. NET MVC下拉列表显示"而不是“描述”
本文关键字:描述 quot MVC NET 列表显示 ASP | 更新日期: 2023-09-27 18:12:02
我一直在做一些关于ASP的教程。. NET MVC,并决定尝试一些我还没有见过的东西。
我有两张表:病人和分类。我希望能够创建一个新的分类,然后当我创建或编辑一个新的病人时,我可以选择一个分类。
现在,作为我的下拉列表中的一个例子,假设我有猫,狗和鱼。如果我选择cat,显示的值将是1,而不是实际的单词"cat"。"
我的问题是,这可以实现与我的代码或它需要一个完整的重写?如果你有其他一般性的建议,请告诉我。
我的控制器:
private PatientContext db = new PatientContext();
private ClassificationContext dbCC = new ClassificationContext();
public ActionResult Index(string sortOrder)
{
return View();
}
public ActionResult Create([Bind(Include = "PatientId,First_Name,Last_Name,Address,City,State,Zipcode,Phone,ClassificationId")] Patient patient)
{
if (ModelState.IsValid)
{
db.Patients.Add(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Classifications = new SelectList(dbCC.Classifications, "ClassificationId", "Description");
return View(patient);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patients.Find(id);
if (patient == null)
{
return HttpNotFound();
}
ViewBag.Classifications = new SelectList(dbCC.Classifications, "ClassificationId", "Description");
return View(patient);
}
病人模型:
public class Patient
{
public int PatientId { get; set; }
[DisplayName("Classification")]
public int ClassificationId { get; set; }
}
分类模型:public class Classification
{
public int ClassificationId { get; set; }
public string Description { get; set; }
}
创建(患者)视图:
<div class="form-group">
@Html.LabelFor(model => model.ClassificationId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*@Html.EditorFor(model => model.ClassificationId)*@
@Html.DropDownListFor(model => model.ClassificationId, (IEnumerable<SelectListItem>)ViewBag.Classifications, "Select Classification")
@Html.ValidationMessageFor(model => model.ClassificationId)
</div>
</div>
编辑(患者)视图:
<div class="form-group">
@Html.LabelFor(model => model.ClassificationId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*@Html.EditorFor(model => model.ClassificationId)*@
@Html.DropDownListFor(model => model.ClassificationId,(IEnumerable<SelectListItem>)ViewBag.Classifications, "Select Classification")
@Html.ValidationMessageFor(model => model.ClassificationId)
</div>
</div>
索引(患者)查看:
<td>
@Html.DisplayFor(modelItem => item.ClassificationId)
</td>
您需要区分SelectListItem.Text
(在下拉列表中显示)和SelectListItem.Value
(绑定到您的模型的值)
将控制器中定义ViewBag.Classifications
的行替换为如下内容:
ViewBag.Classifications = dbCC.Classifications
.Select(c => new SelectListItem { Value = c.ClassificationId, Text = c.Description })
.ToList();