SelectList for many years

This is probably very simple ... I'm trying to create a SelectList containing years from the current, until 2008. It will always be so. For example, in 2020, my SelectList will contain values ​​from 2020 to 2008.

I set up this loop, but I'm not sure what is the best thing to do for this.

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

Is it possible to create one SelectListItem and "add" it to the SelectList for each iteration?

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

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

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

+7
source share
3 answers
 var selectList = new SelectList(Enumerable.Range(2008, (DateTime.Now.Year - 2008) + 1)); 
+15
source

I had to slightly modify the accepted answer in order to work in older browsers. I ended up with a select list missing by such values

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

I had to change 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"); 
+1
source

Instead of adding SelectListItem to SelectList just add it to List<SelectListItem> . The razor can use List<SelectListItem> as a source.

0
source

All Articles