Operator '!' cannot be applied to operand of type '<null>' in Asp.Net Core

Dung Do Tien May 20 2021 267

I have a project in Asp.Net Core, on a listing page, I want to check and display a view component if it satisfies my condition as below:

@{
    var isDisplayCustomer = ViewBag.IsDisplayCustomer;
}

<div class="row max-width">
    @if (!isDisplayCustomer)
    {
        @await Component.InvokeAsync("DisplayCustomerInfo")
    }
</div>

And when running the application I got an error Operator '!' cannot be applied to operand of type '<null>' 

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Operator '!' cannot be applied to operand of type '<null>'
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at AspNetCore.Views_Product_ListCar.ExecuteAsync() in /src/Presentations/WebApp/Views/Customer/ListCustomer.cshtml:line 49
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)

Please tell me how can I resolve it?

Thanks for any suggestion.

Have 2 answer(s) found.
  • K

    Kingtub Kakkak May 20 2021

    This error really throws when your variable is null. So you need to check null before using it.

    @{
        var isDisplayCustomer  = ViewBag.IsDisplayCustomer  != null ? (bool)ViewBag.IsDisplayCustomer : false;   
    }

    I hope it's useful for you.

  • H

    Hieu Nguyen May 20 2021

    n an if-statement you can only have true or false (boolean's basically) but isDisplayCustomer variable is null so it throws an exception. 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:

    @{
       var isDisplayCustomer  = ViewBag.IsDisplayCustomer ??  false;
    }
    <div class="row max-width">
        @if (!isDisplayCustomer)
        {
            @await Component.InvokeAsync("DisplayCustomerInfo")
        }
    </div>

    I hope it works for you!

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close