2013-12-16 34 views
2

第一個元素我有型號,它具有以下字段:DropDownListFor不選擇值時,從收集

public List<SelectListItem> Months 
{ 
    get 
    { 
     return new List<SelectListItem> 
     { 
      new SelectListItem {Text = "111", Value = "1"}, 
      new SelectListItem {Text = "222", Value = "2"} 
     }; 
    } 
} 
public List<TestModel> ServiceTest { get; set; } 

TestModel有一個字段:鑑於

public string Month { get; set; } 

模型ServiceTest = new List<ServiceTest> {new ServiceTest {Month = "2"}};

現在,問題。爲什麼這個

@Html.DropDownListFor(m => m.ServiceTest[0].Month, Model.Months) 

不選擇第二個值。但是這個

@Html.DropDownListFor(m => m.ServiceTest[0].Month, new SelectList(Model.Months, "Value", "Text", Model.ServiceTest[0].Month)) 

工作正確。 我真的不明白爲什麼第一個表達式無法正常工作。

+0

我知道我沒有加入到討論中,但什麼是monthes? : - > –

+0

@MichalB。,哦)這個例子在真實項目中創建得非常快,我沒有注意到這個錯誤。我稍後再糾正這個問題,謝謝 – idlerboris

回答

2

原因是因爲在綁定默認值時,DropDownListFor助手僅支持簡單表達式。比如x => x.SomeProp。在第一個示例中,您正在使用複雜的lambda表達式(子屬性索引器訪問和另一個子屬性)。

你的第二種方法是解決助手的這種限制的正確方法。

+0

謝謝!但我覺得這很奇怪。因爲這個幫手正確識別字段的名稱和ID。如果我使用其他助手(例如TextBoxFor),它正確處理這種情況。爲何不同的行爲? – idlerboris

+0

好吧,別問我。詢問寫這個幫手的人(微軟) –

0

爲了使第一條語句正常工作,您需要提供它所綁定的列表。

在你的類創建一個屬性:

public string[] SelectedMonths { get; set; } 

然後使用:

@Html.DropDownListFor(m => m.SelectedMonths, new SelectList(Model.Monthes, "Value", "Text", Model.SelectedMonths))