I'm using Visual Studio 2019 and I'm getting this error when I'm trying to populate a list. My coworker tried to help me and thought it was strange to get the following error since my list has 27 references to objects, so part of it is being recognized but part of it isn't:
An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object.
Here is some of the models:
public class BogusModel
{
public List<County> Counties { get; set; }
public SelectList CountySelectList { get; set; }
}
Here is where the class for it is in the model:
public class County
{
public string CountyName { get; set; }
public double CountyRate { get; set; }
public County(string CountyName, double CountyRate)
{
this.CountyName = CountyName;
this.CountyRate = CountyRate;
}
public County()
{
}
}
Here is the beginning of the method where I try to populate the list in the model:
public void createAndPopulateCounties()
{
Counties.Add(new County(CountyName = "Allegany", CountyRate = 0.0305));
}
And the controller where the method is called (I commented out the select list since that doesn't work either):
[HttpGet]
public IActionResult Index()
{
BogusModel model = new BogusViewModel();
// Call the method to create and populate the list of counties
model.createAndPopulateCounties();
// model.CountySelectList = new SelectList(model.Counties, "CountyName", "CountyName");
return View("Index", model);
}
My coworker and I tried changing the code in the County class that said this.CountyName = CountyName;
a few different ways, I used to have code like this in my function
List<County> Counties = new List<County>();
but that was a problem since it wasn't populating the original list, it was creating a second one (my coworker noticed that). I can't figure this out from the other stack overflow postings, and none of the other postings mention references to the object. I tried to upload an image of the references, but StackOverflow said it was forbidden. But it does reference the County objects I tried to add, but then I get the runtime error.