如何处理ASP.NET MVC中的拆分日期字段(年,月,日)

时间:2010-07-20 21:45:02

标签: c# asp.net-mvc datetime

我需要在当前项目中为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" })%>

对于这类问题,是否有更好,更优雅的解决方案?也许是自定义模型绑定器?

提前致谢

1 个答案:

答案 0 :(得分:3)

Scott Hansleman写了关于完全相同的问题,并设计了一个DateAndTimeModelBinder,博客文章here。然而,考虑到代码的数量与它为聚会带来的代码,它有更多的写作更少!