我一直在ASP.NET MVC上做一些教程,并决定尝试一些我还没有看过的东西。
我有两张桌子:患者和分类。我希望能够创建新的分类,然后在创建或编辑新患者时,我可以选择分类。
现在,作为我在DropDownList中的例子,我可以说我有猫,狗和鱼。如果我选择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>
答案 0 :(得分:1)
您需要区分SelectListItem.Text
(显示在下拉列表中)和SelectListItem.Value
(这是绑定到模型的值)
使用以下内容替换定义ViewBag.Classifications
的控制器中的行:
ViewBag.Classifications = dbCC.Classifications
.Select(c => new SelectListItem { Value = c.ClassificationId, Text = c.Description })
.ToList();
应该这样做。