Skip to content Skip to sidebar Skip to footer

Dropdownlist Not Behaving As Expected

I'm having trouble with my DropDownListFors that I'm hoping you can help me with. I'm guessing it's one of those things that you either know or you don't. The problem is I have a C

Solution 1:

There's multiple ways to do this. For example you could load the list of countries in you AddressViewModel.

I.e.

publicclassAddressViewModel
{

    [Display(Name = "Country")]
    publicint SelectedCountryId { get; set; }

    public IEnumerable<SelectListItem> Countries { get; set; }
}

Then in your view do this

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

You could also load you Countries list with Javascript.

$(document).ready(function () {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("GetCountries")',  <--This will be a method in your controller that brings back the Countries,
        success: function (results) {
        var options = $('#SelectedCountryId');
        $.each(results, function () {
            options.append($('<option />').val(this.CountryId).text(this.CountryName));
        });
    }
    });

  publicclassCountryViewModel
  { 
       public int CountryId {get;set;}
       public int CountryName {get;set;
  }

In your controller

    [HttpPost]
    public JsonResult GetCountries()
    {
        var countries = //some method to get the countries for a database or somethingvar countriesList = countries .Select(x => new CountryViewModel { CountryId  = x.CountryId, CountryName = x.CountryName }).ToList();
        returnthis.Json(countriesList );
    }

Post a Comment for "Dropdownlist Not Behaving As Expected"