In need splitted date fields for dob (like the facebook registration form) in my current project. I currently have a working solution but this solutions seems a little bit "dirty".
My solution is a DTO for the splitted date and an editor template for this type.
public class SplittedDate
{
public int Day { get; set; }
public int Month { get; set; }
public int Year { get; set; }
public SplittedDate()
: this(DateTime.Today.Day, DateTime.Today.Month, DateTime.Today.Year)
{
}
public SplittedDate(DateTime date)
: this(date.Day, date.Month, date.Year)
{
}
public SplittedDate(int day, int month, int year)
{
ValidateParams(day, month, year);
Day = day;
Month = month;
Year = year;
}
public DateTime AsDateTime()
{
ValidateParams(Day, Month, Year);
return new DateTime(Year, Month, Day);
}
private void ValidateParams(int day, int month, int year)
{
if (year < 1 || year > 9999)
throw new ArgumentOutOfRangeException("year", "Year must be between 1 and 9999.");
if (month < 1 || month > 12)
throw new ArgumentOutOfRangeException("month", "Month must be between 1 and 12.");
if (day < 1 || day > DateTime.DaysInMonth(year, month))
throw new ArgumentOutOfRangeException("day", "Day must be between 1 and max days in month.");
}
}
The editor template code:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SplittedDate>" %>
<%= Html.TextBox("Day", 0, new { @class = "autocomplete invisible" })%>
<%= Html.TextBox("Month", 0, new { @class = "autocomplete invisible" })%>
<%= Html.TextBox("Year", 0, new { @class = "autocomplete invisible" })%>
Is there a better, more elegant solution for this kind of problem? Maybe a custom modelbinder thing?
Thanks in advance