可为空的对象必须具有日期时间错误的值

nullable object must have a value for datetime error

我正在尝试显示当前登录用户的一些用户信息,但我遇到了这个错误:"System.InvalidOperationException: Nullable object must have a value." 我希望 "Birthday" 在 table 中为空,如果未设置,则根本不显示。 我将不胜感激任何帮助。

这是我的代码:

模型视图

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

控制器

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();
}

查看

 <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>

您的问题出现在这条线上:

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

如果 currentUser.Birthday 为空,.Value 将抛出错误。一个建议可以是:

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

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