Tobias Tobias - 2 months ago 17x
reST (reStructuredText) Question

How to build a nested tree with ASP.NET Web API

I'm using ASP.NET Web API 2 for the backend and AngularJS for the frontend. I want to display a treeview in AngularJS.

So I need a nested Model in my ASP Web API. The model currently looks like this:

public class Register
public int ID { get; set; }
public string Name { get; set; }
public List<Register> Children { get; set; }

and the controller like this:

// GET: api/Registers
public IQueryable<Register> GetRegister()
return db.Register;

In my Database I added following examples:


The JSON Output shows:


The first entry looks fine, but I don't want to output the children itself. It it possible to only output the
with its
and not the children itself? Like this:


The second problem is, when I want enter a specific Folder ID (For example
ID 4(RootFolder)
). I only get this as a response:

Specific Entry

Why there are no child elements? The controller is this one:

// GET: api/Registers/5
public IHttpActionResult GetRegister(int id)
Register register = db.Register.Find(id);
if (register == null)
return NotFound();

return Ok(register);


  • How can I filter the Output to only show the
    s with each children but not showing the children objects itself?

  • Why there are no children when I specify a specific ID?


I guess you are using entity framework for database operations. For the first point, you need to filter root folder row e.g. for root Register_ID is null

db.Register.Where(x => x.Register_ID == null && x.ID==ID).ToList()

For second point to load root folder's children you can include it's navigation property, for example refer below code.

db.Register.Include(x => x.Children).Where(x => x.Register_ID == null).ToList();