我有一个自定义数据注释验证器来验证出生日期是否在从今天起 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" })%>
ERROR: The ViewData item that has the key 'JuniorSenior' is of type 'System.String' but must be of type 'IEnumerable'.
这个错误很奇怪,因为那部分代码工作得很好。同样奇怪的是,仅当输入的日期在距今天 150 年之前时才会发生此错误。 因此,仅当出生日期验证失败时才会发生该错误。在调试时,我注意到一旦我删除了自定义数据注释,一切正常并且没有遇到错误。
So that leads me to assume the problem is in my data annotation.
这是我的控制器代码,以防你想看看我想要做什么。
[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);
}
我的 IntializeSelectLists 函数:
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;
}
任何帮助,将不胜感激。