Search code examples
c#asp.net-mvcdatetimeasp.net-identitynullable

nullable object must have a value for datetime error


I'm trying to display some user info for current logged user, and i got stuck with this error: "System.InvalidOperationException: Nullable object must have a value." I want "Birthday" to be blank in the table, or not shown at all if it's not set. I'll appreciate any help.

Here is my code:

Modelview

   public class InfoViewModel
    {   
        public string Id { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }
        public DateTime? Birthday { get; set; }
    }

Controller

public async Task<ActionResult> Index()
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
    var currentUser = manager.FindById(User.Identity.GetUserId());
    ViewBag.Id = currentUser.Id;
    ViewBag.Email = currentUser.Email;
    ViewBag.Phone = currentUser.PhoneNumber;
    ViewBag.FullName = currentUser.FullName;
    ViewBag.Address = currentUser.Address;
    ViewBag.Birthday = currentUser.Birthday.Value.ToString("dd-MM-yyyy");

    return View();
}

View

 <table>
                <tr>
                    <th>@Html.DisplayNameFor(model => model.Id)</th>
                    <td>
                        @ViewBag.Id
                    </td>
                </tr>
                <tr>
                    <th>@Html.DisplayNameFor(model => model.FullName)</th>
                    <td>
                        @ViewBag.FullName
                    </td>
                </tr>
                <tr>
                    <th>@Html.DisplayNameFor(model => model.FirstName)</th>
                    <td>
                        @ViewBag.Firstname
                    </td>
                </tr>
                <tr>
                    <th>@Html.DisplayNameFor(model => model.Birthday)</th>
                    <td>
                        @ViewBag.Birthday
                    </td>
                </tr>
            </table>

Solution

  • Your problem is happening on this line:

    currentUser.Birthday.Value.ToString("dd-MM-yyyy");
    

    If currentUser.Birthday is null, the .Value will throw the error. One suggestion could be:

    ViewBag.Birthday = currentUser.Birthday?.Value.ToString("dd-MM-yyyy");
    

    or

    ViewBag.Birthday = currentUser.Birthday.HasValue ? currentUser.Birthday.Value.ToString("dd-MM-yyyy") : string.Empty;