代码之家  ›  专栏  ›  技术社区  ›  Michael Wallasch

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

  •  1
  • Michael Wallasch  · 技术社区  · 15 年前

    我的解决方案是一个用于分割日期的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?

    提前谢谢

    1 回复  |  直到 15 年前
        1
  •  3
  •   redsquare    15 年前

    斯科特•汉斯勒曼(Scott Hansleman)也写了同样的文章,并设计了一个DateAndTimeModelBinder博客 here . 然而,它有一点写得多做得少的代码量相比,它带来了党!