1

Please check the controller and model bellow. I am trying to add data to a list property of class CreateProductPage_IniViewData but problem is when i try to do it normally in controller it says -

System.NullReferenceException: 'Object reference not set to an instance of an object.'

So whats wrong i am doing? Any idea?

Model:

namespace Demo.ViewModels
{
    public class CreateProductPage_IniViewData
    {
        public string StoreUrl { get; set; }
        public List<ProductGroupFake> productGroup { get; set; }
    }


    public class ProductGroupFake
    {
        public string GroupName { get; set; }
    }

}

Controller:

public IActionResult Index()
{
var finalData = new CreateProductPage_IniViewData();

finalData.productGroup.Add(new ProductGroupFake { GroupName = "foo", });


return View();
}
john Huo
  • 11
  • 4
  • 2
    Well, the error message is pretty self-explanatory. Where do you ever assign `finalData.productGroup = new List();` ? – Rufus L Mar 22 '19 at 00:29
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Tetsuya Yamamoto Mar 25 '19 at 01:45

1 Answers1

0

in here:

var finalData = new CreateProductPage_IniViewData();

the productGroup inside new CreateProductPage_IniViewData is not initialized. simply set it a default value like this:

   public class CreateProductPage_IniViewData
    {
        public string StoreUrl { get; set; }
        public List<ProductGroupFake> productGroup { get; set; } = new List<ProductGroupFake>();
    }

Or just initialize it before adding to it:

var finalData = new CreateProductPage_IniViewData();
finalData.productGroup = new List<ProductGroupFake>();
finalData.productGroup.Add(new ProductGroupFake { GroupName = "foo"});
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171