non-nullable type 'System.DateTime' , ASP.NET MVC

前端 未结 1 1802
[愿得一人]
[愿得一人] 2021-01-23 07:10

I have a registration page, and because of content issues we have to request and enforce applicants giving a birthdate. So it stands to reason that this field cannot be null.

相关标签:
1条回答
  • 2021-01-23 07:39

    Have the birthdate parameter be a nullable DateTime, i.e., DateTime?, then check if it is null, set a model error, and rerender the view with the error when it is null.

    [CaptchaValidator]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(string name, string email, string password, string validation, bool agreement, DateTime? birthdate)
    {
        ValidateRegistration( name, email, password, validation, agreement, birthdate );           
        if (ModelState.IsValid)
        {
        }
        return View();
    }
    
    private bool ValidateRegistration(string name, string email, string password, string validation, DateTime? birthdate)
    {
         if (!birthdate.HasValue)
         {
             this.ModelState.AddModelError( "birthdate", "You must supply a birthdate." );
         }
    
         ...
    
    0 讨论(0)
提交回复
热议问题