Inside a loop I’m trying to add an object with the type Location to a List<Location> property.
CONTROLLER:
[HttpPost]
public ActionResult Index([Bind(Include = "CitySearch")]HomeViewModel model)
{
List<CityIdentity> ids = null;
ids = service.GetNamesId(model.CitySearch);
foreach (var id in ids)
{
var loc = service.GetLocation(id.CityId);
var location = new Location
{
CityId = id.CityId,
Place = loc.Place,
};
model.Locations.Add(location);
}
}
VIEWMODEL:
public class HomeViewModel
{
public string CitySearch { get; set; }
public List<Location> Locations { get; set; }
}
model is of type HomeViewModel and property Locations is of type List<Location>. model is instance from form HttpPost action from submitting the form in the View.
I’m debugging and the error’s occurs at model.Locations.Add(location) and I’m getting object reference not set to an instance of an object. and nullref exception.
Any idea?
Based on your reactions and the context, it seems your
Locationsproperty isn’t initialized at the time, so you can’t use a methodAddon this collection. To overcome this issue, you need to initialize this property first and then you can manipulate it whatever way you need to.One way of achieving this is to initialize your
Locationsproperty in the constructor of your model (or wherever you see fit).So just add something like this and you’re good to go:
This initializes your property enough to use its methods.