ASP.NET MVC 模型将单独的日、月、年字符串字段绑定到单个 DateTime 对象

ASP.NET MVC Model bindING separate day, month, year string fields to single DateTime object

我目前正在构建一个表单,要求用户输入他们的出生日期。我确定最用户友好的方法是通过单独的日期、月份和年份输入字段。

我有一个强类型视图,其中包含生日、出生月份和出生年份的文本框。将表单发布到服务器后,我需要将这些发布的字符串值转换为正确的 DateTime 对象。我目前正在执行年龄验证测试的自定义验证器中生成此 DateTime 对象,但我相信有更好的方法。

到目前为止,我已尝试在模型构造函数中构建 DateTime 对象,如下所示:

public class Applicant
{
    [Required(ErrorMessage = "Day Required")]
    public string DobDay { get; set; }
    [Required(ErrorMessage = "Month Required")]
    public string DobMonth { get; set; }
    [Required(ErrorMessage = "Year Required")]
    [BirthDateValidation("DobDay", "DobMonth")]
    public string DobYear { get; set; }

    public DateTime BirthDate { get; set; }

    public Applicant()
    {
        this.BirthDate = new DateTime(Convert.ToInt32(this.DobYear), Convert.ToInt32(this.DobMonth), Convert.ToInt32(this.DobDay));
    }
}

有没有办法使这个任务更加自动化,正如我在上面尝试过的那样,以便在将表单发布到服务器时,使用发布的生日、出生月份、出生年份表单自动构建 DateTime 对象价值观?

使用自定义模型活页夹:

public class MyCustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
                            ModelBindingContext bindingContext)
    {
        HttpRequestBase request = controllerContext.HttpContext.Request;

        string day = request.Form.Get("DobDay");
        string month = request.Form.Get("DobMonth");
        string year = request.Form.Get("DobYear");
        //etc..
        return new Applicant
        {
            BirthDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day))
            //etc..
        };
    }
}

[HttpPost]
public ActionResult Save([ModelBinder(typeof(MyCustomBinder))] Applicant applicant)
{
    return View();
}