2010-07-06 91 views
0

長話短說,我試圖向ViewData添加一些額外的項目以使我的生活更輕鬆,並且它的邊緣案例並不真正證明其自己的模型僅適用於這一例。繼續閱讀更多具體細節。ASP.NET MVC使用DropDownList的強類型化視圖

所以我有一個強類型的編輯視圖爲我的一個對象,一切都很好,直到我試圖將一個下拉列表放在視圖上,並且ID與我的類的屬性不匹配。

我有這個

public class MyModel 
{ 
    public String Name {get;set;} 
    public int ID {get;set;} 
    public MyOtherModel Other {get;set;} 
} 
public class MyOtherModel 
{ 
    public String Name {get;set;} 
    public int ID {get;set;} 
} 

我能夠更新Name屬性。

我也想從DropDownList中設置Other.ID屬性,但它不讓我這樣做。

我的控制器看起來像這樣

public ActionResult EditView() 
{ 
    var da = new DataAccessClass(); 
    var Names = da.ReadActive(); // returns MyOtherModel 
    var sli = new SelectList(evNames, "ID", "Name"); 
    ViewData["OtherModelNames"] = sli; 
    return View(); 
} 

我的視圖看起來是這樣的:

<p> 
    <label for="EndTime">Name:</label> 
    <%= Html.TextBox("Name") %> 
    <%= Html.ValidationMessage("Name", "*")%> 
</p> 
<p> 
    <label for="EndTime">Other Name:</label> 
    <%= Html.DropDownList("OtherNameIDList", (SelectList)ViewData["OtherModelNames"]) %> 
    <%= Html.ValidationMessage("OtherNameIDList", "*")%> 
</p> 

我得到一個錯誤,在這條線<%= Html.DropDownList("OtherNameIDList", (SelectList)ViewData["Names"]) %>

「沒有ViewData的項目與關鍵'IEnumerable'類型的'OtherNameIDList'。「

我的期望是,在接受POST的控制器操作中,我將手動使用FormCollection []讀出該ID並使用正確的ID填充MyOtherModel。

+0

一個問題是,您在您的操作中設置ViewData [「OtherModelNames」],但在視圖中期待ViewData [「名稱」]。 – Tahbaza 2010-07-06 20:07:01

+0

謝謝,我修正了這個問題,因爲這個問題是匿名的。 ;) – Nate 2010-07-06 20:18:13

回答

1

在控制器嘗試:

public ActionResult EditView() 
{ 
    var da = new DataAccessClass(); 
    var Names = da.ReadActive(); // returns MyOtherModel 
    var sli = new SelectList(evNames, "ID", "Name"); 
    ViewData.Add("OtherModelNames", new SelectList("ID", "Name", "")); 
    return View(); 
} 

的視圖

Html.DropDownList("OtherModelNames") 

要在下拉列表獲得Other.Id,只在類中創建一個靜態INT:

public static int OtherId {get { return this.Other.Id; }}