Dayan
Dayan

Reputation: 8031

Trying to understand DropDownListFor, default selection is showing up twice?

The following code "works", but the final results are not what I expected. I get a dropdownlist with all countries as expected; the default being United States at the very top of the list. But, United States still remains as selectable if you scroll down the list, I now have two "United States" entries...

Also worth noting that in my validation, the default "United States" selection is consider invalid, that is, it shows me validation message to "please select a country". If I then select the "United States" entry located further down the list, the validation message disappears.

Why is this happening? Am I understanding this incorrectly?

VIEW MODEL

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]" })

CONTROLLER

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

   return model;
}

Upvotes: 0

Views: 172

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Obviously it will shown two times inside the drop-down list because one time it is populated from database using GetCountriesDropdownListPopulated() and second one that is shown is because you are adding it as default text which in most cases we put Select One or Select Country, so you need to select default selection inside the GetCountriesDropdownListPopulated() method.

Upvotes: 1

user3786581
user3786581

Reputation: 421

please set the AppendDataBoundItems="false" in DropDownList

For Example:

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

Upvotes: 0

Related Questions