通常當我使用DropDownListFor助手時,我選擇基於ID(int)選擇哪個項目,但現在我有一種情況,我需要顯示哪個項目被選中基於文本(字符串)而不是ID。在該模型是否被正確設置爲我想與這個屬性的值時,控制器:MVC 4 DropDownListFor基於文本設置選定的項目
model.Title
一個例子標題是「前臺」。我在我的控制器下面的代碼:
ViewBag.Titles = new SelectList(jobTitles, "Name", "Name");
,並在視圖上我有這樣的:
@Html.DropDownListFor(model => model.Title, ViewBag.Titles as SelectList)
DropDownList控件與所有預期職稱正確填充,它只是不選擇根據model.Title正確的職位名稱。我究竟做錯了什麼?
UPDATE:
好像有別的東西可能在我的代碼去錯了,所以我把所有的在這裏看到,如果我做錯了什麼。
控制器:
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))
你的'JobTitle.SelectAll()'返回'列表'?或另一種類型的對象? –
Paritosh