Your model class should contain the following properties;public struct DatePart { public static IEnumerable<int> DayItems { get { return Enumerable.Range(1, 31); } } public static IEnumerable<String> MonthItems { get { return new System.Globalization.DateTimeFormatInfo().MonthNames; } } public static IEnumerable<int> YearItems { get { return Enumerable.Range(DateTime.Now.Year - 30, 30 + 1); } } }
public int Day { get; set; } public int Month { get; set; } public int Year { get; set; }
Create SelectListItem Date, Month and Year collections and add them to the ViewBag.
In the view, create dropdowns and populate them with collections in the ViewBag.ViewBag.Days = DatePart.DayItems.Select(d => new SelectListItem { Text = d.ToString() }); ViewBag.Months = DatePart.MonthItems.Select((m, i) => new SelectListItem { Value = (i + 1).ToString(), Text = m }); ViewBag.Years = DatePart.YearItems.Select(y => new SelectListItem { Text = y.ToString() });
It is important that the select element names match the property names in the model.@Html.DropDownList("Day", (IEnumerable<SelectListItem>) ViewBag.Days) @Html.DropDownList("Month", (IEnumerable<SelectListItem>) ViewBag.Months) @Html.DropDownList("Year", (IEnumerable<SelectListItem>) ViewBag.Years)
Now, in your controller method you can access the selected values as follows:
var selectedTime = new DateTime(model.Year, model.Month, model.Day);