Thursday, October 23, 2014

Create Separate Dropdowns for Day, Month, Year in ASP.NET MVC

Create a structure that will hold the Month, Day and Year fields:

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);
            }
        }
    }
Your model class should contain the following properties;

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.

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() });
In the view, create dropdowns and populate them with collections in the ViewBag.
@Html.DropDownList("Day", (IEnumerable<SelectListItem>) ViewBag.Days)
@Html.DropDownList("Month", (IEnumerable<SelectListItem>) ViewBag.Months)
@Html.DropDownList("Year", (IEnumerable<SelectListItem>) ViewBag.Years)
It is important that the select element names match the property names in the model.

Now, in your controller method you can access the selected values as follows:
var selectedTime = new DateTime(model.Year, model.Month, model.Day);