Reputation: 2313
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
Upvotes: 10
Views: 8917
Reputation: 3215
I created a function to help me out with this. It will reverse it automatically depending on the values you give it.
Check it out, let me know what you think and if you can improve upon it:
public static IEnumerable<SelectListItem> Years(int from, int to, int? value = default(int?)) {
var reverse = from > to;
var min = reverse ? to : from;
var max = reverse ? from : to;
var years = Enumerable.Range(min, max - min);
if (reverse) {
years = years.Reverse();
}
return years.Select(year => new SelectListItem {
Value = year.ToString(),
Text = year.ToString(),
Selected = value.Equals(year),
});
}
Use:
Years(DateTime.Now.Year, DateTime.Now.Year + 4)
/* result: (currently 2018)
2018
2019
2020
2021
*/
Years(DateTime.Now.Year + 4, DateTime.Now.Year, 2019)
/* result: (currently 2018)
2021
2020
2019 (selected)
2018
*/
Upvotes: 0
Reputation: 436
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");
Upvotes: 2
Reputation: 245479
var selectList =
new SelectList(Enumerable.Range(2008, (DateTime.Now.Year - 2008) + 1));
Upvotes: 22
Reputation: 1365
Rather than add a SelectListItem
to a SelectList
, simply add it to a List<SelectListItem>
. Razor can use a List<SelectListItem>
as a source.
Upvotes: 0