首页 > 解决方案 > 可为空的对象必须具有日期时间错误的值

问题描述

我正在尝试为当前登录的用户显示一些用户信息,但我遇到了这个错误:“System.InvalidOperationException:Nullable object must have a value。” 我希望“生日”在表格中为空白,或者如果未设置则根本不显示。我会很感激任何帮助。

这是我的代码:

模型视图

   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>

标签: c#asp.net-mvcdatetimeasp.net-identitynullable

解决方案


您的问题发生在这一行:

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

如果 currentUser.Birthday 为 null,.Value则会抛出错误。一个建议可能是:

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

或者

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

推荐阅读