我有一个定制的数据注释验证器 来验证出生日期 从今天起150年
以下是我自定义的数据注释:
public class DateOfBirthRange : RangeAttribute
{
public DateOfBirthRange()
: base(typeof(DateTime), DateTime.Now.AddYears(-150).ToShortDateString(), DateTime.Now.ToShortDateString()) { }
}
像这样使用它:
[Required(ErrorMessage = "BirthDate is required.")]
[DisplayName("Birth Date")]
[DateOfBirthRange(ErrorMessage = "BirthDate must be between {1:M/d/yyyy} and {2:M/d/yyyy}")]
public DateTime BirthDate { get; set; }
这是一个非常奇怪的问题,因为我回来的错误与数据说明无关。
<%: Html.DropDownListFor(m => m.JuniorSenior, (IEnumerable<SelectListItem>)ViewData["seniority"], new { @class = "input-small" })%>
此错误是奇怪的, 因为代码的这部分功能完全正常 。 < enger> 是什么也使这个错误变得奇怪 : 此错误仅在输入日期在今天150年之前时才发生 。 strong > 因此该错误只在出生验证日期失效时才发生 。 由于我正在调试, 我注意到, 一旦我删除了自定义的数据注释, 一切正常, 没有出错 。
这是我的控制器代码 以防你想知道我想做什么
[HttpPost]
public ActionResult Save(PatientModel patModel, FormCollection values)
{
// remove white space form text box fields
patModel.FirstName = values["FirstName"].Trim();
patModel.LastName = values["LastName"].Trim();
patModel.Initials = values["Initials"].Trim();
patModel.StreetAddress1 = values["StreetAddress1"].Trim();
patModel.StreetAddress2 = values["StreetAddress2"].Trim();
patModel.PostalCode = values["PostalCode"].Trim();
if (ModelState.IsValid)
{
try
{
// Pull the long form of the gender into the model.
if (!String.IsNullOrEmpty(values["genders"]))
{
patModel.Gender = values["genders"];
}
// Profile is valid, save it.
if (_Service.SaveProfile(Session["username"].ToString(), Session["password"].ToString(), patModel))
ViewData["SaveProfile"] = true;
else
ViewData["SaveProfile"] = false;
}
catch (Exception ex)
{
logger.Error("Function Name: Save Message: " + ex.Message + "");
}
}
IntializeSelectLists(patModel);
if (patModel.Title == "Select")
patModel.Title = "";
if (patModel.JuniorSenior == "Select")
patModel.JuniorSenior = "";
return View("Index", patModel);
}
My Intialize 选择列表函数 :
public void IntializeSelectLists(PatientModel pm)
{
seniority = new[] { "Select", "Jr.", "Sr." };
List<SelectListItem> JuniorSenior = new List<SelectListItem>();
foreach (string item in seniority)
{
SelectListItem alb = new SelectListItem { Text = item, Value = item };
JuniorSenior.Add(alb);
}
ViewData["seniority"] = JuniorSenior;
}
任何帮助都将不胜感激。