Tom Stickel
Tom Stickel

Reputation: 20411

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

I am calling a project (WCF, but that shouldn't matter) that consumes a IList , with MVC 3 (which really should not matter either obviously) I want to convert a single column List of strings (IList which is just a list of Countries) into a List

Hard Coded list I have done like this and they work fine:

 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 the List to SelectListItem, anyone do this? Yes.. I have search and found several examples, but none that really fit my specific need.

Upvotes: 5

Views: 21529

Answers (2)

Nelson
Nelson

Reputation: 29

In Controller ,

   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();

In View ,

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

Upvotes: 0

Laurent
Laurent

Reputation: 3837

You can use LINQ as such:

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

Or I think you can just use one of SelectList's constructors:

public SelectList BirthPlace { get; set; }

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

Upvotes: 17

Related Questions