2014-07-01 58 views
0

下面的代碼「有效」,但最終的結果並不符合我的預期。如預期的那樣,我得到了所有國家的dropdownlist;默認情況下,美國位於列表的最頂端。但是,如果你向下滾動列表,美國仍然可以選擇,我現在有兩個「美國」條目...試圖理解DropDownListFor,默認選擇顯示兩次?

另外值得注意的是,在我的驗證中,默認的「美國」選擇被認爲是無效的,也就是說,它向我顯示驗證信息「請選擇一個國家」。如果我選擇位於列表下方的「美國」條目,則驗證消息將消失。

這是怎麼發生的?我理解錯誤嗎?

視圖模型

public class ProfileViewModel 
{ 

    public class CountriesDropdown 
    { 
     public string defaultSelection { get; set; } 
     public IEnumerable<SelectListItem> dropdownViewModel { get; set; } 
    } 

    public CountriesDropdown countriesDropdownViewModel { get; set; } 

    [Required] 
    [DataType(DataType.Text)] 
    [StringLength(100)] 
    [Display(Name = "Country of Residence: ")] 
    public string CountryResidence { get; set; } 
} 

VIEW

@Html.DropDownListFor(p => p.CountryResidence, Model.countriesDropdownViewModel.dropdownViewModel, Model.countriesDropdownViewModel.defaultSelection, new { style = "max-width: 215px;", id = "cbCountry", @class = "validate[required]" }) 

控制器

private ProfileViewModel PopulateAllDropdown(ProfileViewModel model) 
{ 
    model.countriesDropdownViewModel = new ProfileViewModel.CountriesDropdown(); 
    model.countriesDropdownViewModel.dropdownViewModel = _DBCall.GetCountriesDropdownListPopulated(); 
    model.countriesDropdownViewModel.defaultSelection = "United States"; 

    return model; 
} 
+0

當然,它會顯示兩次它從數據庫中彈出,第二個是默認文本,在大多數情況下選擇一個或選擇國家 –

+0

cab你顯示GetCountriesDropdownListPopulated()定義你需要設置默認從他們的 –

+0

中選擇一個謝謝Ehsah Sajjad,在閱讀您的評論後,我能夠修復它。我移動了'GetCountriesDropdownListPopulated()'代碼中的默認選擇,並且正常工作。爲什麼不把它作爲答案發布,以便我可以接受它? – Dayan

回答

1

很顯然,這將示出的下拉列表內的兩個時間,因爲一次它從數據庫中使用GetCountriesDropdownListPopulated()和第二一個是填充顯示是因爲你將其作爲在大多數情況下,我們把選擇一個選擇國家默認文本,所以你需要選擇GetCountriesDropdownListPopulated()方法內默認的選擇。

0

請設置AppendDataBoundItems =「假」中的DropDownList

對於實施例

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="false"> 
    </asp:DropDownList>