Created
June 9, 2016 18:09
-
-
Save kdarty/af45cf08dddd5a2cc932505f5df7e218 to your computer and use it in GitHub Desktop.
For those times when you need to create a DropDownList for a range of Years, you can easily do that through "Enumerable.Range". The sample code below will create a list that ranges from 1900 to the next most Current Year and then Sort that list in Descending Order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NOTE: This requires a USING clause for System.Web.Mvc | |
var selectListItems = new List<SelectListItem>(); | |
// Add Default Selection | |
selectListItems.Add(new SelectListItem | |
{ | |
Text = "-- Make a Selection --", | |
Value = "0", | |
Selected = true | |
}); | |
// Get the Value of Next Year (i.e. This Year + 1) | |
var nextYear = DateTime.Now.AddYears(1).Year; | |
// Build a List of Years based on the Range from 1900 to Current Year + 1 | |
var yearList = new SelectList(Enumerable.Range(1900, nextYear - 1900 + 1)); | |
// Order Year List Descending | |
selectListItems.AddRange(yearList.OrderByDescending(y => y.Text)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment