Tobias Tobias - 3 months ago 40
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:

DBExample

The JSON Output shows:

[{"ID":4,"Name":"RootFolder","Children":[{"ID":5,"Name":"Sub1","Children":null}]},{"ID":5,"Name":"Sub1","Children":null}]


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

{"ID":4,"Name":"RootFolder","Children":[{"ID":5,"Name":"Sub1","Children":null}]}


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
[ResponseType(typeof(Register))]
public IHttpActionResult GetRegister(int id)
{
Register register = db.Register.Find(id);
if (register == null)
{
return NotFound();
}

return Ok(register);
}


Summary:


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

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


Answer

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();