faloi
faloi

Reputation: 401

MVC4 Web Api doesn't serialize my class

I've developed a very simple WebApi in order to test some Knockout.js features. IMO it should work properly, but when I make a GET request to the Api via Fiddler, it doesn't return any JSON at all.

I'm using MVC4's JSON default serializer.

This is my model...

public class Page
{
    public string Name { get; set; }
    public List<Control> Controls { get; set; }        
}

public abstract class Control
{
    public string Name { get; set; }
    public abstract string SayHi();
}

public class Form : Control
{
    public override string SayHi()
    {
        return string.Format("Hi, I'm form {0}", Name);
    }
}

public class Datagrid : Control
{
    public override string SayHi()
    {
        return string.Format("Hi, I'm datagrid {0}", Name);
    }
}

...here is my Controller...

public class PageController : ApiController
{
    static readonly ISimplePageRepository _repository = new TestPageRepository();

    // GET /api/page
    public IEnumerable<Page> GetAllPages()
    {
        return _repository.GetAll();
    }
}

...and just in case, this is my repo...

public class TestPageRepository : ISimplePageRepository
{
    private List<Page> _pages = new List<Page>();

    public TestPageRepository()
    {
        Add(new Page {Name = "pagina1", Controls = new List<Control>() {new Datagrid() {Name = "laTablita"}}});
        Add(new Page {Name = "pagina2", Controls = new List<Control>() {new Form() {Name = "elFormito"}}});
    }

    public Page Add(Page item)
    {
        _pages.Add(item);
        return item;
    }

    public IEnumerable<Page> GetAll()
    {
        return _pages.AsQueryable();
    }
}

Thanks in advance!

Upvotes: 1

Views: 913

Answers (1)

faloi
faloi

Reputation: 401

I changed the default serializer to JSON.NET and it worked. Apparently, the problem was with the default serializer and the abstract Control class.

Upvotes: 1

Related Questions