c# - 可为空的对象必须具有日期时间错误的值
问题描述
我正在尝试为当前登录的用户显示一些用户信息,但我遇到了这个错误:“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>
解决方案
您的问题发生在这一行:
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;
推荐阅读
- recaptcha - reCaptcha v3:即使我没有令牌,我也应该发布到 Google 的验证 API 吗?
- c# - 有没有办法在运行时有条件地将属性公开给 WCF 客户端?
- python - 未登录时运行 Python Windows 服务
- c - 如何检查目标代码是否为 16/32 位?
- javascript - 获取数组中搜索结果的索引
- .htaccess - 如何使用 .htaccess 过滤目录列表
- mysql - 如何使用 directus cms 编辑现有的 mysql 表?
- haproxy - haproxy 随机响应状态码 503
- c++ - Mac OS 上 QT 中的错误导入 boost 库
- r - 使用 dplyr 合并包含相似字符串的行