我的解决方案是一个用于分割日期的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" })%>
对于这类问题有没有更好、更优雅的解决方案?也许是定制的modelbinder?
提前谢谢