3

這讓我完全困惑。DropDownListFor SelectedItem問題

這是我的觀點:

@Html.DropDownListFor(model => model.ScoreDescription, 
           Model.RatingOptions, 
           "--", 
           new { @id = clientId }) 

和模型:

public decimal? Score { get; set; } 
public SelectList RatingOptions 
{ 
    get 
    { 
     var options = new List<SelectListItem>(); 

     for (var i = 1; i <= 5; i++) 
     { 
      options.Add(new SelectListItem 
      { 
       Selected = Score.HasValue && Score.Value == Convert.ToDecimal(i), 
       Text = ((decimal)i).ToRatingDescription(ScoreFactorType), 
       Value = i.ToString() 
      }); 
     } 

     var selectList = new SelectList(options, "Value", "Text"); 
      // At this point, "options" has an item with "Selected" to true. 
      // Also, the underlying "MultiSelectList" also has it. 
      // Yet selectList.SelectedValue is null. WTF? 
     return selectList; 
    } 
} 

由於意見建議,我不能得到所選擇的值發生。

這是否與我使用可空的decimal這個事實有關?在那個循環之後,options是正確的,因爲它正好有1個選項爲true的項目,所以看起來我做的是正確的事情。現在

,如果我使用一個不同SelectList超載:

var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty; 
var selectList = new SelectList(options, "Value", "Text", selectedValue); 

它的工作原理。爲什麼?起初,我認爲這可能是一個LINQ技巧(例如推遲執行),但我試圖強制.ToList(),沒有什麼區別。

這就像設置Selected屬性一樣,因爲您創建的SelectListItem沒有任何效果,您可以使用 ctor參數在最後設置它。

任何人都可以對此有所瞭解嗎?

回答

4

如果你看看SelectList類的實現,它實際上並沒有使用你傳遞SelectListItem的事實。它適用於IEnumerable。因此不使用SelectListItemSelected屬性。我個人更喜歡設置所選的下拉列表的值,方法是設置您綁定ddl的相應屬性的值。

實施例:

public int? Score { get; set; } 
public SelectList RatingOptions 
{ 
    get 
    { 
     var options = Enumerable.Range(1, 5).Select(i => new SelectListItem 
     { 
      Text = ((decimal)i).ToRatingDescription(ScoreFactorType), 
      Value = ((decimal)i).ToString() 
     }); 
     return new SelectList(options, "Value", "Text"); 
    } 
} 

,然後在控制器的動作簡單地將Score屬性設置爲所需的值,並在視圖中使用此分數屬性綁定到:

@Html.DropDownListFor(
    model => model.Score, 
    Model.RatingOptions, 
    "--", 
    new { @id = clientId } 
) 
+2

右鍵,所以基本上我的最後一句是正確的 - 在這種情況下,SelectListItem的Selected屬性是毫無意義的。乾杯。 – RPM1984 2011-05-05 06:36:26