Credit Card Expiration Date ASP.NET MVC SelectList Sample Code

A couple weeks ago I wrote about how to create credit card expiration date drop downs for your ASP.NET application.  Today I had to do the same thing but in ASP.NET MVC.  For the most part I was able to use the same logic but instead of slowly building up the drop down list items, in ASP.NET MVC I created a SelectList which is constructed from an IEnumerable object containing the collection of items to display. 

From the MSDN Documentation for SelectList:

SelectList Constructor (IEnumerable, String, String, Object)
Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.

In ASP.NET MVC you can use the Html.DropDownList helper to create the dropdownlist from a SelectList object:

<%= Html.DropDownList("ExpMonth", Model.ExpMonthSelectList)%>
<%= Html.DropDownList("ExpYear", Model.ExpYearSelectList)%>

But the problem is what IEnumerable object could I use to contain the month and year information but also has data value and data text parts? This is where the System.Collections.Generic.KeyValuePair structure comes in:

//Create the credit card expiration month SelectList
List<KeyValuePair<string, string>> expirationDateMonths = new List<KeyValuePair<string, string>>();
for (int i = 1; i <= 12; i++)
{
    DateTime month = new DateTime(2000, i, 1);
    expirationDateMonths.Add(new KeyValuePair<string, string>(month.ToString("MM"), month.ToString("MMM (M)")));
}
this.ExpMonthSelectList = new SelectList(expirationDateMonths, "key", "value", DateTime.Today.ToString("MM"));

//Create the credit card expiration year SelectList (go out 12 years) 
List<KeyValuePair<string, string>> expirationDateYears = new List<KeyValuePair<string, string>>();
for (int i = 0; i <= 11; i++)
{
    String year = (DateTime.Today.Year + i).ToString();
    expirationDateYears.Add(new KeyValuePair<string, string>(year, year));
}
this.ExpYearSelectList = new SelectList(expirationDateYears, "key", "value", DateTime.Today.Year.ToString());

 

Technorati Tags: ,

1 Comment

Comments have been disabled for this content.