我需要编写一个返回下一个10年选择列表的函数。 我现在很难编码,仍然在努力完成这项工作。如何编写一个可以返回我想要的任何时期的函数,例如未来20年
//View
@Html.DropDownListFor(model => model.CardExpiryYear, vmConstants.listExpiryYears)
//Partial Class
public static partial class vmConstants
{
public static SelectList listExpiryYears = new SelectList(new[]
{
new{ Name ="" , ID = ""},
new{ Name ="2014" , ID = "2014"},
new{ Name ="2015" , ID = "2015"},
new{ Name ="2016" , ID = "2016"},
new{ Name ="2017" , ID = "2017"},
new{ Name ="2018" , ID = "2018"},
new{ Name ="2019" , ID = "2019"},
new{ Name ="2020" , ID = "2020"},
new{ Name ="2021" , ID = "2021"},
new{ Name ="2022" , ID = "2022"},
new{ Name ="2023" , ID = "2023"},
new{ Name ="2024" , ID = "2024"},
new{ Name ="2025" , ID = "2025"},
new{ Name ="2026" , ID = "2026"},
},
"ID", "Name", 1);
}
答案 0 :(得分:6)
您应该可以使用Enumerable.Range
和DateTime.Now.Year
。这样的事情应该让你开始。
var years = Enumerable.Range(DateTime.Now.Year, 10);
var select = new SelectList(years.Select(y => new SelectListItem()
{
Text = y.ToString(), Value = y.ToString()
}));