Steve Steve - 3 months ago 26
C# Question

How to populate list as class object?

How do you populate a list as a class object? For example, this does not work:

[DataContract]
public class JsonReviewFormFields
{
[DataMember]
public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}

public class PersonalDevelopmentPlan
{
public List<ShortTerm> shortTerm { get; set; }
public List<LongTerm> longTerm { get; set; }
}

public class ShortTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}

public class LongTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}


This is controller action:

public JsonReviewFormFields GetReviewForm()
{
PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();

List<ShortTerm> _itemsShort = new List<ShortTerm>();
_itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;

List<LongTerm> _itemsLong = new List<LongTerm>();
_itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.longTerm = _itemsLong;

return jsonReviewFormFields;
}


The code crashes at

jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;


It's probably a basic object orientated error. How do you populate the list?

Answer

You are not instantiating it, you have to instantiated the type first:

jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();

and then set property of it:

jsonReviewFormFields.personalDevelopmentPlan.shortTerm =  _itemsShort

before that you also have to instantiate main class which i don't see in your controller action anywhere :

JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();