2012-01-20 88 views
0

我是mvc的新手,需要一些幫助。 我有這個模型類:獲取所選下拉列表項的ID

Public Class PostCategories 


Public Property ID() As Integer 


Public Property Name() As String 

Public Property Slug() As String 

Public Property ParentID() As Integer 

,我有這個下拉列表在我看來:

@Html.DropDownList("IDList", New SelectList(Model, "Id", "ID"), "Selected Parent") 

相反ID的,我希望把名稱在下拉列表和ID保存到分貝。我該怎麼做?需要幫助請。

回答

1

假設你的視圖模型是PostCategories的名單,然後只需使用:

@Html.DropDownList("IDList", New SelectList(Model, "ID", "Name"), "Selected Parent") 
0

正如Beyers說,這應該足以更改您的代碼

@Html.DropDownList("IDList", New SelectList(Model, "ID", "Name"), "Selected Parent") 

,其中的第二個參數SelectList構造函數是您希望在表單提交時傳遞的所選項目的值,並且必須反映您的某個模型屬性的名稱,因此必須是「ID」而不是「Id」。 第二個參數是項目的名稱顯示在下拉列表中,在這種情況下,您應該使用「名稱」,因爲它可能是您要使用的屬性。 (可選)您可以在頁面加載時傳入第四個參數,即所選值。

另一種方法是建立在控制器你的SelectList和使用ViewBag這樣傳遞:

ViewBag.PostCategoriesId = new SelectList(yourPostCategoriesList, "ID", "Name"); 

,然後在查看您的代碼會是這樣:

@Html.DropDownList("PostCategoriesId", string.Empty)