I have a custom data annotation validator to validate the date of birth to be between 150 years from today.
Here is my custom data annotation:
public class DateOfBirthRange : RangeAttribute
{
public DateOfBirthRange()
: base(typeof(DateTime), DateTime.Now.AddYears(-150).ToShortDateString(), DateTime.Now.ToShortDateString()) { }
}
Using it like this:
[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; }
This is a very strange problem because the error that I'm getting back has nothing to do with the data annotation. Its causing an error in my view here:
<%: 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'.
That error is strange because that part of the code is working perfectly fine. What also makes this strange is that this error only occurs when the date entered is before 150 years from today. So that error only occurs when the date of birth validation fails. As I was debugging, I noticed that once I remove the custom data annotation, everything works fine and no error is encountered.
So that leads me to assume the problem is in my data annotation.
Here is my controller code in case you want to see what I'm trying to do.
[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 IntializeSelectLists function:
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;
}
Any help would be appreciated.