2009-02-26 50 views
5

在我的控制,我有以下幾點:Html.DropDownList在ASP.NET MVC RC(刷新)沒有預先選擇項目

ViewData["myList"] = 
    new SelectList(itemRepository.GetAll(), "Id", "Name", currentItem.Id); 

並在視圖我有:

<%= Html.DropDownList("myItem", (SelectList)ViewData["myList"])%> 

呈現的下拉列表應該具有預先選擇的currentItem.Id的Id的項目,但它不包含。沒有選擇,所以它默認爲第一個。

在我更新到RC/RC(刷新)之前,這工作。有任何想法嗎?

+0

這仍然是我與MVC 1.0面臨的問題 – 2009-06-11 02:48:15

回答

6

如果您將ViewData中的鍵的名稱與視圖上的表單字段的名稱相匹配,HtmlHelpers被設計爲隱式地從ViewData中取出,基於那把鑰匙。我建議改變你的視圖代碼:

<%= Html.DropDownList("myList") %> 

的HtmlHelpers似乎以這種方式使用的時候效果最好(雖然這並不總是可能的)。

更新:

擴大後爲什麼這似乎而其他方法不,我一頭扎進了SelectExtensions.cs代碼工作的原因...

但是你打電話的DropDownList ,私有方法SelectInternal最終呈現實際的HTML。對於SelectInternal簽名是這樣的:

SelectInternal(string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, bool allowMultiple, IDictionary<string,object> htmlAttributes) 

下面是DropDownList中的兩種用法採取的路徑:

的DropDownList( 「myList中」)

DropDownList(string name) -> 
SelectInternal(null, name, htmlHelper.GetSelectData(name), true, false, null) 

的DropDownList( 「myItem」 ,(SelectList)ViewData [「myList」]) DropDown

List(string name, IEnumerable<SelectListItem> selectList) -> 
DropDownList(name, selectList, null /* object, htmlAttributes */) -> 
DropDownList(name, selectList, new RouteValueDictionary(htmlAttributes)) -> 
SelectInternal(null, name, selectList, false, false, htmlAttributes) 

因此,在這一天結束的時候,這兩個路徑之間的區別在於工作方式通過真正到SelectInternal的usedViewData參數,而不能上班的路上經過

這很可能,我認爲有一個bug某處內SelectInternal時usedViewData

0

對我來說(使用MVC RC刷新)

在視圖中的以下工作:

<%= Html.DropDownList("NAME_OF_ITEM_ID_PROPERTY", (SelectList)ViewData["myList"]) %> 

因此,對於你的例子,很可能是:

<%= Html.DropDownList("Id", (SelectList)ViewData["myList"]) %> 
+0

嗨凱,會不會使名稱和ID「ID」?這將是錯誤的,因爲我需要名稱和id是'myItem',因爲這是表單提交正在尋找的id。 – 2009-02-26 13:00:40

+0

你試過了嗎?檢查呈現的HTML。 我的理解是,在您的控制器中,您將值字段定義爲項目模型的ID,並將名稱定義爲SelectListItem的值。 因此,通過將下拉菜單中的第一個參數設置爲Id,您可以請求此值字段。 – 2009-02-26 16:10:04

0

我只是做了我自己的下拉幫手。也許不如內置的效率高,但確實有效。