Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Month Dropdown in C# ASP.NET MVC

This method seems stupid and a bit heavy; is there a more optimal way of creating the same thing (its for an MVC View Dropdown)

private List<KeyValuePair<int, string>> getMonthListDD {     get     {         var dDur = new List<KeyValuePair<int, string>>();         dDur.Add(new KeyValuePair<int, string>(1, "January"));         dDur.Add(new KeyValuePair<int, string>(2, "Febuary"));         dDur.Add(new KeyValuePair<int, string>(3, "March"));         dDur.Add(new KeyValuePair<int, string>(4, "April"));         dDur.Add(new KeyValuePair<int, string>(5, "May"));         dDur.Add(new KeyValuePair<int, string>(6, "June"));         dDur.Add(new KeyValuePair<int, string>(7, "July"));         dDur.Add(new KeyValuePair<int, string>(8, "August"));         dDur.Add(new KeyValuePair<int, string>(9, "September"));         dDur.Add(new KeyValuePair<int, string>(10, "October"));         dDur.Add(new KeyValuePair<int, string>(11, "November"));         dDur.Add(new KeyValuePair<int, string>(12, "December"));          return dDur;     } } 
like image 993
Chris McKee Avatar asked May 26 '10 09:05

Chris McKee


2 Answers

In your view model you could have a Months property:

public IEnumerable<SelectListItem> Months {     get      {         return DateTimeFormatInfo                .InvariantInfo                .MonthNames                .Select((monthName, index) => new SelectListItem                {                    Value = (index + 1).ToString(),                    Text = monthName                });     } } 

which could be directly bound to a DropDownListFor:

<%= Html.DropDownListFor(x => x.SelectedMonth, Model.Months) %> 
like image 141
Darin Dimitrov Avatar answered Sep 21 '22 21:09

Darin Dimitrov


Simplicity is gold, so in your View:

<select id="month">     @for (Int16 i = 0; i < 12; i++)     {         <option value="@i">@DateTimeFormatInfo.InvariantInfo.MonthNames[i]</option>     } </select> 
like image 27
George Avatar answered Sep 23 '22 21:09

George