Нужно разделить поля даты для dob (например, регистрационную форму в Facebook) в моем текущем проекте.В настоящее время у меня есть рабочее решение, но оно кажется немного «грязным».
Мое решение - DTO для разделенной даты и шаблон редактора для этого типа.
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.");
}
}
код шаблона редактора:
<%@ 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" })%>
Есть ли лучшее, более элегантное решение для такого рода проблем?Может быть, что-то особенное для модели?
Заранее спасибо