简体   繁体   中英

C# Instance of Lists In Data Model

I've not been able to find an answer so am posting this. If this has already been answered then please point me in that direction.

I have a class model in MVC as below:

public class SearchModel
{
    public int id { get; set; }
    public string ActivityName { get; set; }
    public string Subject { get; set; }
    public string Level { get; set; }      
    public List<LocationModel> Locations { get; set; }
}

public class LocationModel
{
    public int LocationID {get; set;}
    public string Location { get; set; }
}

I am trying to populate the Locations list in my code but can't seem to get the code to create an instance of it properly.

I have a List of SearchModel as there are multiple items. This is populating fine by doing the following:

List<SearchModel> items = new List<SearchModel>();

and then looping through the following to populate the model.

SearchModel item = new SearchModel();
item.ActivityName = reader["ActivityName"].ToString();
item.Level = reader["LevelNames"].ToString();
item.Subject = reader["SubjectNames"].ToString();
item.id = Convert.ToInt32(reader["ActivityID"]);
items.Add(item);

How do I add the data to the Locations List in the SearchModel? This will contain multiple records also.

item.Locations = new List<LocationModel>();

you can add some data in it

var myLocationModel = new LocationModel();
myLocationModel.Location = "Africa";
item.Locations.Add(myLocationModel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM