Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SelectList for years

This is probably really simple... I am trying to create a SelectList containing years from the current one, back until 2008. This will always be the case. For example, in the year 2020, my SelectList will contain values from 2020 - 2008.

I set up this loop, but I'm not sure what the best place to go with this is

for (int i = currentYear; i != 2009; --i)
{

}

Is it possible to create a single SelectListItem and "add" it to a SelectList for each iteration?

I don't think my statement above is possible, so my next thought was to create a list of years, then use LINQ to create it.

var selectList = ListOfYears.Select(new SelectListItem
{
    Value =
    Text = 
});

But then I'm not entirely sure how to get the value from the list. Thanks

like image 418
Jeff Avatar asked Dec 19 '12 18:12

Jeff


2 Answers

var selectList = 
    new SelectList(Enumerable.Range(2008, (DateTime.Now.Year - 2008) + 1));
like image 103
Justin Niessner Avatar answered Nov 15 '22 19:11

Justin Niessner


I had to change the accepted answer slightly to work in older browsers. I ended up with a select list missing the values like this

<option value="">1996</option><option value="">1997</option>

I had to alter the code above to this

var yr = Enumerable.Range(1996, (DateTime.Now.Year - 1995)).Reverse().Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
        return new SelectList(yr.ToList(), "Value", "Text");
like image 44
Don Avatar answered Nov 15 '22 20:11

Don