How to create dropdown list for months and years on MVC

The solution involves two dropdowns (select) menu: one for months one for years. Before I go the solution, it's important to note that Microsoft.Net returns 13 months rather than 12 months even for the Gregorian calendar. You can read more information about why .Net have 13-month names? on an MSDN blog.

Dropdown list for months and years

Let's get first the months. Although only month number make sense, it's also good experience adding the month name as well.

var months = DateTimeFormatInfo
    .InvariantInfo
    .MonthNames
    .TakeWhile(monthName => monthName != String.Empty)
    .Select((monthName, index) => new SelectListItem
    {
        Value = (index + 1).ToString(CultureInfo.InvariantCulture),
        Text = string.Format("({0}) {1}", index + 1, monthName)
    });

    @Html.DropDownList("month", months)

You need a decision when it comes to credit card expiration year. Since there is no official guideline for the credit card issuers to choose when the cards expire. My decision is 15 years and has never heard any complaint from my clients. But it's worth to note that Amazon goes 20 years while PayPal 19 years.

var years = Enumerable
    .Range(DateTime.Now.Year, 15)
    .Select(year => new SelectListItem
    {
        Value = year.ToString(CultureInfo.InvariantCulture),
        Text = year.ToString(CultureInfo.InvariantCulture)
    });

    @Html.DropDownList("year", years)