I thought it would be an easy task, but I’m struggling for a while now already.
I have Sport object which belongs to some SportGroup object.
I want to represent groups inside a combobox, and I created SportViewModel.cs with the following properties
public Guid Id {get; set;}
public string Name {get; set;}
public Guid? SportGroupId { get;set; }
public IEnumerable<SportGroup> SportGroups {get; set; }
HttpGet create action
SportViewModel newSport = new SportViewModel();
newSport.SportGroups = new SelectList(GetAllSportGroups(), "Id", "Name");
//GetAllSportGroups() returns list of SportGroups domain objects as you can imagine.
My create view looks like this
@model Models.SportViewModel
<div>Sport group</div>
<div>@Html.DropDownListFor(x => x.SportGroupId, Model.SportGroups)</div>
Now on the controller’s httpPost action I receive the data and try to save it:
[HttpPost]
public ActionResult Create(SportViewModel newSport)
{
// if model state is valid and other checking omitted
// session and transaction omitted
Sport sport = new Sport();
sport.Id = newSport.Id;
sport.Name = newSport.Name;
SportGroup sportGroup = session.Load<SportGroup>(SportGroupId);
sport.SportGroups.Add(sportGroup); // here is where I'm getting an error
}
After submitting I’m getting these error
Object reference not set to an instance of an object.
Referencing linesport.SportGroups.Add(sportGroup);
Please help.
Thanks
Try this:
Because otherwise:
If this
.SportGroupsproperty is NOT properly instantiated, it will be NULL and you cannot call.Add()on it! You’ll get that exact exception that you have.This is typically something you would best do in the constructor of the
Sportclass – make sure that all contained collections etc. are also initalized and instantiated when you create a new object of typeSport