通常,当我使用 DropDownListFor 助手时,我会根据 ID(int)选择哪个项目,但现在我需要根据文本(字符串)而不是 ID 显示选择了哪个项目。在控制器中,模型被正确设置为我想要的这个属性的值:
model.Title
一个示例标题是“前台”。我的控制器中有以下代码:
ViewBag.Titles = new SelectList(jobTitles, "Name", "Name");
在我看来,我有这个:
@Html.DropDownListFor(model => model.Title, ViewBag.Titles as SelectList)
DropDownList 正确填充了所有预期的职位,只是没有根据model.Title选择正确的职位。我究竟做错了什么?
更新:
我的代码中似乎还有其他可能出错的地方,所以我将所有这些都放在这里,看看我是否做错了什么。
控制器:
public ActionResult Edit(int id = 0)
{
StaffMember staffmember = StaffMember.SelectByID(id); // gets staff member from db
ViewBag.Titles = new SelectList(JobTitle.SelectAll(), "Name", "Name", staffmember.Title); // JobTitle.SelectAll() returns List<JobTitle>
StaffEditModel model = new StaffEditModel();
model.ID = staffmember.ID;
model.ClientID = staffmember.ClientID;
model.FirstName = staffmember.FirstName;
model.MiddleInitial = staffmember.MiddleInitial;
model.LastName = staffmember.LastName;
model.Title = staffmember.Title;
model.Phone = staffmember.Phone;
model.Email = staffmember.Email;
model.Birthday = staffmember.Birthday;
model.HireDate = staffmember.HireDate;
model.Biography = staffmember.Biography;
if (staffmember == null)
{
return HttpNotFound();
}
return View(model);
}
模型:
public class StaffEditModel
{
public int ID { get; set; }
public int ClientID { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Middle Initial")]
public string MiddleInitial { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string Title { get; set; } // this is the property I'm trying to show in DropDown
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public string Birthday { get; set; }
[Display(Name = "Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public string HireDate { get; set; }
public string Email { get; set; }
[MaxLength(14)]
public string Phone { get; set; }
public string Biography { get; set; }
}
看法:
@Html.DropDownListFor(model => model.Title, new SelectList(ViewBag.Titles,"Value","Text", Model.Title))