René Kåbis
René Kåbis

Reputation: 892

Unable to populate selectlist from model

The details:

I seem to be tying myself up in knots here, trying to get a list of countries to be displayed in a drop-down select list.

My model:

[DisplayName("Country")]
public string Country { get; set; }
private IEnumerable<SelectListItem> _CountryList;
public IEnumerable<SelectListItem> CountryList {
  get {
    List<string> CultureList = new List<string>();
    CultureInfo[] getCultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
    foreach(CultureInfo getCulture in getCultureInfo) {
      RegionInfo GetRegionInfo = new RegionInfo(getCulture.LCID);
      if(!CultureList.Contains(GetRegionInfo.EnglishName)) {
        CultureList.Add(GetRegionInfo.EnglishName);
      }
    }
    return CultureList.OrderBy(x => x.ToString()).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }).ToList();
  }
  set { _CountryList = value; }
}

My View:

@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, "Value", "Text"), " « ‹ Choose your country › » ", htmlAttributes: new { @class = "form-control" })

The error message that comes back is the ever-infuriating,

System.NullReferenceException: Object reference not set to an instance of an object.

Which is code for, “You f**ked up, and good luck figuring out what it is because I am not telling”.

I have gone so far as to try to manually fill the model with a manually-crafted select list, to zero effect. Where am I going wrong here?


EDIT 1:

I have now tried,

RegionInfo country = new RegionInfo(new CultureInfo("en-US", false).LCID);
List<SelectListItem> countryNames = new List<SelectListItem>();

//To get the Country Names from the CultureInfo installed in windows
foreach(CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) {
  country = new RegionInfo(new CultureInfo(cul.Name, false).LCID);
  countryNames.Add(new SelectListItem() { Text = country.DisplayName, Value = country.DisplayName });
}

//Assigning all Country names to IEnumerable
IEnumerable<SelectListItem> nameAdded = countryNames.GroupBy(x => x.Text).Select(x => x.FirstOrDefault()).ToList().OrderBy(x => x.Text);
return nameAdded;

with zero success. Same results - “u dun goofed”.


EDIT 2:

Model:

[DisplayName("Country:")]
public string Country { get; set; }
public IEnumerable<SelectListItem> CountryList { get; set; }

View:

@Html.DropDownListFor(model => model.Country, Model.CountryList, " « ‹ Choose your country › » ", htmlAttributes: new { @class = "form-control" })

Controller:

namespace Project.Controllers {
  public class HomeController : Controller {
    public ActionResult Index() {
      return View();
    }

    public ActionResult Demo() {
      var model = new DemoViewModel() {
        model.CountryList = CountryList.getCountries()
      };
      return View(model);
    }
  }
//dummy content, just to try to "populate" ****ANYTHING****
  public class CountryList {
    public static IEnumerable<SelectListItem> getCountries() {
      IList<SelectListItem> items = new List<SelectListItem> {
      new SelectListItem{Text = "United States", Value = "B"},
      new SelectListItem{Text = "Canada", Value = "B"},
      new SelectListItem{Text = "United Kingdom", Value = "B"},
      new SelectListItem{Text = "Texas", Value = "B"},
      new SelectListItem{Text = "Washington", Value = "B"}
      };
      return items;
    }
  }
}

You see where I try to attach CountryList.getCountries() to the model.CountryList:

Cannot initialize 'DemoViewModel' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

tears out hair

Upvotes: 3

Views: 1179

Answers (1)

Shyju
Shyju

Reputation: 218732

Assuming CountryList.getCountries() returns a collection of SelectListItem,

Do either

var model = new DemoViewModel(); 
model.CountryList = CountryList.getCountries();
return View(model);

Here you are creating an object of DemoviewModel class and setting the CountryList property explicitly.

or this

var model = new DemoViewModel {
                                   CountryList = CountryList.getCountries()
                              };
 return View(model);

This is called Object initialization. Here you are creating an object and initializing the CountryList property value along with that.

Assuming your DemoViewModel class another property to hold the selected item.

public class DemoViewModel
{
  public List<SelectListItem> CountryList { set;get;}
  public string Country { set;get;}
}

Now in your view which is strongly typed to this view model,you use DropDownListFor helper method.

@model DemoViewModel
@using(Html.BeginForm())
{
  @Html.DropDownListFor(s=>s.Country,Model.CountryList)
  <input type="submit" />
}

Upvotes: 3

Related Questions