出生日期自定义范围数据注释不起作用(中断页面)

本文关键字:中断 不起作用 自定义 范围 数据 注释 出生日期 | 更新日期: 2023-09-27 18:35:12

我有一个自定义的数据注释验证器来验证出生日期是否在从今天起 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);
        }

My 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;
        }

任何帮助将不胜感激。

出生日期自定义范围数据注释不起作用(中断页面)

在撞了一下我的头之后,我终于找到了问题所在。

在我的IntializeSelectLists()中,我在JuniorSenior列表之前填充了性别列表。事实证明,pm.Gender返回 null,因此导致异常。

它在m.JuniorSenior崩溃的原因是因为我在m.Gender之前显示了这一点。所以m.JuniorSenior总是空的,因为代码没有达到填充m.JuniorSenior的程度。

patModel.Gender = values["genders"].Trim();

我通过在Save()中添加它来解决问题。

感谢所有花时间帮助我:)