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
var selectList =
new SelectList(Enumerable.Range(2008, (DateTime.Now.Year - 2008) + 1));
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With