简体   繁体   English

SelectList多年

[英]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. 这可能非常简单......我正在尝试创建一个包含当前版本的SelectList ,直到2008年。这将始终如此。 For example, in the year 2020, my SelectList will contain values from 2020 - 2008. 例如,在2020年,我的SelectList将包含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? 是否可以创建单个SelectListItem并将其“添加”到每个迭代的SelectList中?

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. 我不认为上面的陈述是可能的,所以我的下一个想法是创建一个年份列表,然后使用LINQ来创建它。

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");

Rather than add a SelectListItem to a SelectList , simply add it to a List<SelectListItem> . 而不是将SelectListItem添加到SelectList ,只需将其添加到List<SelectListItem> Razor can use a List<SelectListItem> as a source. Razor可以使用List<SelectListItem>作为源。

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
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM