Reputation: 1601
I have a model "Team" with one property "TeamMembers" which is a list of the class "TeamMember". "TeamMember" itself right now only has the Id and Name Properties for testing.
I created the CRUD Views automaticall and can enter the normal properties of "Team" (Id, TeamName, Location, etc.) just fine, but of course the View doesn't know what to do with List, so (just for testing purposes) I hardcoded this into the create method:
var TeamMembers = new List<TeamMember>();
TeamMembers.Add(new TeamMembers { Name = "Bob" });
Team.TeamMembers = TeamMembers;
This seems to work. When I create the new Team, and set a breakpoint right at the end of the Create method, I can see the entry in the inspector/hover. Also a table "TeamMember" (I save the model in a local DB) is created in the DB with and entry for "bob", including a Team_Id referencing the Team I just created.
Now when I try to output the Details for a Team, TeamMembers returns "null". No error, nothing, just "null". Shouldn't it return something? anything? An Object, a Reference,...?
The goal is to create a Team and have TeamMembers contain a whole bunch of TeamMember entries that I can later iterate through and output them in a list, etc.
Can anybody tell me where my mistake lies? Is there a concept I didn't grasp, or some stupid oversight?
Thank you for your time.
Upvotes: 1
Views: 55
Reputation: 33306
You have a minor typo, you are adding TeamMembers
to TeamMembers
.
It should be as follows (I lowercased the TeamMembers
variable too):
var teamMembers = new List<TeamMember>();
teamMembers.Add(new TeamMember { Name = "Bob" });
Team.TeamMembers = teamMembers;
You also need to make sure that you are returning your model in your action i.e
[HttpGet]
public ActionResult Index()
{
var team = new FooModel();
var teamMembers = new List<TeamMember>();
teamMembers.Add(new TeamMember { Name = "Bob" });
team.TeamMembers = teamMembers;
return View(team);
}
Upvotes: 0
Reputation: 1809
You should always instantiate lists in the constructor of your class. I do not know what kind of DB or ORM you use (Entity?) but more often than not the framework will instantiate your classes with the public empty constructor and then set the properties. That could be why.
That why everytime you work on an instance of Team you are sure the list is not null.
public class Team
{
public Team()
{
TeamMembers = new List<TeamMember>();
}
// ...
public List<TeamMember> TeamMembers { get; set; }
}
Then you simply have to do this instead :
// TeamMembers is not null anymore
var team = new Team();
team.TeamMembers.Add(new TeamMember { Name = "Bob" });
Upvotes: 1