javascript - 运算符 '!' 无法应用于类型为 '<null> 的操作数

标签 javascript asp.net-mvc operator-keyword viewbag

我正在使用 MVC 5 ViewBag 并尝试这样做

@if (!ViewBag.UserLoggedIn) {
   <a onclick="javascript:UserSessionManager.UserLogout()">LogOut</a>
}

但出现错误:

Operator '!' cannot be applied to operand of type '<null>'

最佳答案

在 if 语句中,只能有 truefalse(基本上是 boolean),但属性 UserLoggedIn<如果未设置, 将不会存在于 ViewBag 上,因此将为 null。因此,ViewBag.UserLoggedIn 可以是 nullstring。您必须将字符串(也可以为 null)转换为 bool 值才能在 if 语句中使用它。像这样的事情会起作用:

@{
    bool isUserLoggedIn = ViewBag.UserLoggedIn ?? false;
}

@if (!isUserLoggedIn) {
   <a onclick="javascript:UserSessionManager.UserLogout()">LogOut</a>
}

关于javascript - 运算符 '!' 无法应用于类型为 '<null> 的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106954/

相关文章:

c# - 如何在 EF Core 中查询多对多关系

C++ 运算符重载 - 调用函数以获取重载中的值

javascript - 添加类来匹配语句

c# - 任何新列在 Entity Framework 中都是空值

javascript - geolocation.getCurrentPosition 问题

android - 了解长轮询 : client (android) and server (asp net)

flutter - Dart Flutter 中的 "!"是什么?

C++ 流二次插入运算符

javascript - 如何将日期从单词格式化为数字?前任。 2004 年 11 月 4 日至 11/04/2004 使用 JQuery?

javascript - map 略微移动或单击后才会显示标记