【发布时间】:2019-06-30 22:30:47
【问题描述】:
我正在使用 SelectList 在我的视图中填充下拉列表。它适用于 Create 和 Edit 视图以将 ID 值数据存储在表中。如何检索“名称”值以显示在详细信息视图中?
型号
Public Class Employee {
[Key]
public int ID { get; set;}
public string UserName {get; set; }
public byte Gender { get; set; }
}
视图模型
public class EmployeeEditViewModel {
public int ID { get; set; }
public string UserName { get; set; }
public SelectList GenderList { get; set; }
public EmployeeEditViewModel () {
GenderList = CommonHelper.GenderList(null);
}
}
助手
public static SelectList GenderList(object selected)
{
return new SelectList(new[]
{
new { Value = 0, Name = "Male" },
new { Value = 1, Name = "Female" }
}
, "Value", "Name", selected);
}
编辑视图
@model Models.ViewModel.EmployeeEditViewModel
@using (Html.BeginForm()) {
@Html.HiddenFor(model => model.ID)
<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.GenderList, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Gender, Model.GenderList, "- Select -", new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.GenderList, "", new { @class = "text-danger" })
</div>
</div>
}
控制器
[HttpPost]
public ActionResult CreateEmployee(EmployeeEditViewModel emProfile)
{
try
{
if (ModelState.IsValid)
{
Employee newUser = new Employee();
newUser.UserName = emProfile.UserName;
newUser.Gender = emProfile.Gender;
userRepository.Add(newUser);
userRepository.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception ex)
{ }
return View(emProfile);
}
到目前为止效果很好,我能够创建、编辑员工记录,并且 1 或 0 存储在性别表中。 但是,当我想在详细信息视图中显示员工数据时,如何获取文本“男性”或“女性”?
【问题讨论】:
-
创建一个 DetailsViewModel。您不需要该列表,只需在控制器操作中填充一个性别描述即可。
-
使用
Enum,因为你有男性和女性的整数值,这样枚举就可以正确映射而无需进一步创建模型
标签: asp.net-mvc entity-framework-6