Search code examples
javascriptasp.net-mvcoperator-keywordviewbag

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


I am using MVC 5 ViewBag and trying to do

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

but getting an error:

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

Solution

  • In an if-statement you can only have true or false (boolean's basically) but the property UserLoggedIn wont exist on the ViewBag if it's not set and will therefor be null. So ViewBag.UserLoggedIn can be null or a string. You have to cast the string (which can also be null) to a boolean in order to use it in the if-statement. Something like this will work:

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