我目前正在建立一个要求用户输入出生日期的表格。我已经确定,最方便用户使用的方法是通过单独的日期,日期,月份和年份输入字段。
我有一个强类型视图,其中包含生日,出生月份和出生年份的文本框。将表单发布到服务器后,我需要将这些发布的字符串值转换为正确的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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句