2009-09-03 83 views
0

這是我的數據模型類的樣子:兩個數據源創建視圖

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'." 

我很確定我做錯了。填充下拉框的正確方法是什麼?

回答

0

我相信ViewData是用來將信息傳遞給你的視圖,但它不能正常工作。也就是說,ViewData不會從Request.Form設置。我想你可能想要改變你的代碼,如下所示:

// change following 
employeeToAdd.Position = new Position {Title = (string)ViewData["Positions"]}; 
// to this? 
employeeToAdd.Position = new Position {Title = (string)Request.Form["Positions"]}; 

祝你好運!

+0

P.S.你在'

+0

中缺少's'什麼是for屬性? – 2009-09-03 05:33:18

+0

它應該匹配標籤和輸入。例如,對於使用屏幕閱讀器的人來說,這是爲了獲得更好的可訪問性,因此他們知道他們應該填寫什麼內容。我建議的改變是否工作? – Funka 2009-09-03 06:40:00

1

由於未設置ViewData [「位置」],因此在Create()(WITH POST ATTRIBUTE)員工中,您正在收到此錯誤。這個值應該構成你的發佈請求的一部分,並且在帖子從應用中獲取它或者從會話/緩存中獲取它時重新綁定,如果你需要重新綁定它的話。

記住ViewData僅適用於當前請求,所以對於發佈請求ViewData [「職位」]尚未創建,因此此例外。

你可以做一個快速測試...重寫控制器的OnActionExecuting方法,並把邏輯放在那裏取位置,這樣它總是可用的。這應該是需要對每個動作的數據來完成......這僅僅是在這種情況下,測試目的...

// add the required namespace for the model... 
protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    // add your logic to populate positions here... 
    ViewData["Positions"] = new SelectList(from p in _positions.GetAllPositions() select p.Title); 

} 

有可能對本等清潔解決方案,以及可能使用自定義的模型綁定...

3

您可以存儲:

(string)ViewData["Positions"]}; 
在頁面上hiddn標籤

然後調用它像這樣

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Create(Employee employeeToAdd, string Positions) 
{ 
+0

嗯,在隱藏字段中存儲的東西聽起來像Webforms的東西。有沒有更好的方式來做到這一點?它可能只適用於一個或兩個字段,但想象一下,如果您有一個包含15個不同字段的表單,可從數據模型中獲取其數據。那會變得非常難看。 – 2009-09-03 05:35:25

+0

我認爲行動方法看起來不錯,但我不相信隱藏的輸入應該是必要的。 '字符串位置'應該根據在保管箱中選擇的內容自動綁定。 – Funka 2009-09-03 06:45:52