user5448913
user5448913

Reputation:

Convert my List<int> into a List<SelectListItem>

I have a DropDownList containing a range of ten years (from 2010 to 2020) created like such :

var YearList = new List<int>(Enumerable.Range(DateTime.Now.Year - 5, ((DateTime.Now.Year + 3) - 2008) + 1));
ViewBag.YearList = YearList;

But here's my problem, I wish to have a default value selected and keep this value when I submit my information and I wish to use the type List<SelectListItem> for it, since its more practical.

Once in this type I will simply do as such to keep a selected value:

foreach (SelectListItem item in list)
            if (item.Value == str)
                item.Selected = true;

How may I convert my List<int> into a List<SelectListItem> ?

Upvotes: 17

Views: 39895

Answers (3)

CodingCretin
CodingCretin

Reputation: 441

There is now an even cleaner way to do this:

SelectList yearSelectList = new SelectList(YearList, "Id", "Description"); 

Where Id is the name of the list item's value, and Description is the text. If you like you can add a parameter after this to specify the selected item. All you gotta do it pass in the ICollection that you wish to convert to a select list!

In you view you do this:

@Html.DropDownListFor(m => m.YearListItemId,
                        yearSelectList as SelectList, "-- Select Year --",
                        new { id = "YearListItem", @class= "form-control", @name= 
"YearListItem" })

Upvotes: 22

Jason Evans
Jason Evans

Reputation: 29186

You can use LINQ to convert the items from a List<int> into a List<SelectListItem>, like so:

var items = list.Select(year => new SelectListItem
{
    Text = year.ToString(),
    Value = year.ToString()
});

Upvotes: 14

User2012384
User2012384

Reputation: 4919

Try converting it using Linq:

List<SelectListItem> item = YearList.ConvertAll(a =>
                {
                    return new SelectListItem()
                    {
                        Text = a.ToString(),
                        Value = a.ToString(),
                        Selected = false
                    };
                });

Then the item will be the list of SelectListItem

Upvotes: 29

Related Questions