Search code examples
c#asp.net.netasp.net-mvcrazor

Why do I Get Null Error When Checking if(a!=null)


When I try to if (productVariantViewModels != null) returns a null error. I don't understand why this happens? .net framework 4.6 a cshtml page

Edit.cshtml:

@{
ViewBag.Title = "Edit";

List<ProductVariantViewModel> productVariantViewModels = ViewBag.ProductVariantViewModels;
}

...
...
...

                               
 if (productVariantViewModels != null)
 {
     foreach (var item in productVariantViewModels)
     {

        ...

     }
 }
   

Also ProductVariantViewModel:

   public class ProductVariantViewModel
{
    public Products Product { get; set; }
    public string VariantName { get; set; }
    public Variant Variant { get; set; }
    public List<ProductAttribute> VariantAttributes { get; set; }
    public List<string> VariantValues { get; set; }


}

          

error img here


Solution

  • If you want to put the value in the list, it is not initialized and therefore null. This is causing your Null Exception.

    You must first initialize the list with new List<ProductVariantViewModel>(value).

    And you should check if ViewBag or ViewBag.ProductVariantViewModels is null.

    Try this:

    (ViewBag?.ProductVariantViewModels != null)
        List<ProductVariantViewModel> productVariantViewModels = List<ProductVariantViewModel>(ViewBag.ProductVariantViewModels);