這是我的數據模型類的樣子:兩個數據源創建視圖
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Position Position { get; set; }
}
public class Position
{
public string Title { get; set; }
}
我有一個創建視圖,我想爲姓和名,然後兩個文本框有位置標題的下拉框。我試圖做這樣說:
視圖(僅相關部分):
<p>
<label for="Position">Position:</label>
<%= Html.DropDownList("Positions") %>
</p>
控制器:
//
// GET: /Employees/Create
public ActionResult Create()
{
ViewData["Positions"] = new SelectList(from p in _positions.GetAllPositions() select p.Title);
return View();
}
//
// POST: /Employees/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Employee employeeToAdd)
{
try
{
employeeToAdd.Position = new Position {Title = (string)ViewData["Positions"]};
_employees.AddEmployee(employeeToAdd);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
然而,當我點擊提交,我得到這個異常:
System.InvalidOperationException was unhandled by user code
Message="There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Positions'."
我很確定我做錯了。填充下拉框的正確方法是什麼?
P.S.你在'
中缺少's'什麼是for屬性? – 2009-09-03 05:33:18
它應該匹配標籤和輸入。例如,對於使用屏幕閱讀器的人來說,這是爲了獲得更好的可訪問性,因此他們知道他們應該填寫什麼內容。我建議的改變是否工作? – Funka 2009-09-03 06:40:00