Converting IList <string> to MVC.SelectListItem needs explicit casting

I invoke a project (WCF, but that doesn’t matter) that IList consumes, with MVC 3 (which really shouldn't matter either obviously). I want to convert a single row list column (IList, which is just a list of countries) to a list

Hard coded list. I did it like this and they work great:

 public List<SelectListItem> mothermarriedatdelivery = new List<SelectListItem>();
 mothermarriedatdelivery.Add(new SelectListItem() { Text = "Yes", Value = "1" });

However, now I am trying to convert this code:

 public List<SelectListItem> BirthPlace { get; set; }
 BirthPlace = new List<SelectListItem>();
 GetHomeRepository repo = new GetHomeRepository();
 BirthPlace = repo.GetCountries();

I need to implicitly convert from a list to SelectListItem, will anyone do this? Yes .. I have a search and found several examples, but none of them match my specific need.

+5
source share
2

LINQ :

BirthPlace = repo.GetCountries()
                 .Select(x => new SelectListItem { Text = x, Value = x })
                 .ToList();

, SelectList:

public SelectList BirthPlace { get; set; }

BirthPlace = new SelectList(repo.GetCountries());
+18

   var result = proxy.GetAllLocations();

   ViewBag.Area = result.Where(p => p.ParentId == null).Select(p => new SelectListItem { Text = p.LocationName, Value = p.LocationId.ToString() }).ToList();

   ViewBag.Locations = result.Where(p => p.ParentId != null).Select(p => new SelectListItem { Text = p.LocationName, Value = p.LocationId.ToString() }).ToList();

   return View();

@Html.DropDownList("LocationName", ViewData["Area"] as IEnumerable<SelectListItem>) 
0

All Articles