You will be amazed at how simple it is. Just set up the model objects so that they have the correct properties. With the JSON string you are trying to reach, you donβt need a view model because you think the top-level object contains employee properties. If you use the viewmodel, then the top-level object will be the view model object, and the employee will be a property of this object.
Instead, I think you want the top-level object to be an employee with a property that is a list of child objects (child objects). Child objects also have a property called children. Which can be populated recursively. Creating an object is your responsibility, but I provided some pseudo-code with pseudo-data to get you started.
public Class Employee { public int EmployeeID {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public List<Child> Children {get; set;} } public Class Child { public int ChildID {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public List<Child> Children {get; set;{ }
Now your action method. Do you know you can just return JsonResult? Do it:
public JsonResult GetJSON() { //Build employee object and add children to list. Something like the following pseudo-code: List<Child> childrenList = new List<Child> { new Child { ChildID = //some id, FirstName = "Joe", LastName = "Smith" // Add children to list. }, // Add more children to list. } Employee emp = new Employee { EmployeeID = 123, FirstName = "John", LastName = "Doe", Children = childrenList }; Return Json(emp); }
This JSON will look like this:
{ "EmployeeID":"123", "FirstName":"John", "LastName":"Doe", "Children":[ { "ChildID":"someid", "FirstName":"Joe", "LastName":"Smith", Children [] }, { etc... } ] }
If you are not familiar with JSON, then you should be aware that the quotation marks around the variable and name ensure that nothing is interpreted incorrectly. MVC does this for you, and not bad. It will turn the employee list property into a JSON array without any work on your part, and it will format the JSON neatly and readily.
Now with MVC 3 you can also bind the model to JSON. If you make a request with the json object enabled, MVC 3 will automatically bind its properties to the employee object. Therefore, if you send the same JSON string as above, your action method might look like this:
public ActionResult SampleMethod(Employee emp) {
NOTE. You might want to change Employee to Person and assign it a Children property of type List<Person> . Thus, you combine the classes Employee and Child in one. But, of course, I donβt see all your code, so perhaps you have enough unique properties to deserve two classes.