Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Jul 15, 2012 03:17 PM by agent_smith
Jul 13, 2012 10:37 PM|LINK
I am looking for examples on how to use Web API for ViewModels or similar classes containing 'related' items.
I have a Person class. The Persons API has GetAllPersons(), GetPerson(string id), etc.
Can I create a complex type (like a view model) of a Person and all of their related items, such as a list of phone numbers?
How do I create more controller actions for different scenarios such as this?
Jul 13, 2012 11:19 PM|LINK
Just create a controller specific for that viewmodel. The ApiController would behave exactly the same way and send back a json object or xml representing the view model.
Jul 14, 2012 12:35 AM|LINK
Are you saying there are a finite number of controller actions per controller?
Meaning, unlike a controller that returns views, an API controller can only have a few actions?
Basic CRUD for a particular entity, but I would need additioanl controllers for complex models made of different classes joined together?
Jul 14, 2012 07:15 PM|LINK
Yes, by default there are a finite number of methods (there aren't actions in the ApiController). You have several methods that correspond to particular HTTP verbs (GET, POST, PUT and Delete)
But that has nothing to do with your question about complex models, what I'm saying is that for complex models, create a completely new controller that is in charge of loading those complex models that contain both the Person object and anything else you
It's a good practice to have several controllers anyway and not try to jam everything into one big controller.
Jul 15, 2012 03:17 PM|LINK
Thanks. So what are the 'finite' number of methods?
Is it 5?
Read all, read one by key, update, delete, create?
I would not jam everything into one controller, but similar to MVC actions, there are things that are logically grouped.
For example, if I have a 'Customer' controller and want to API customer data, then I would think 'CustomerOrders' would be a logical grouping of API data under 'Customers' by some key field.
What you are saying is that I need a new controller called 'CustomerOrders' or something?
In that case, there would be only a method for CustomerOrders(guid id) or something that returns the complex object like one single customer and then the list of related orders.
That seems like I would end up with a lot of controllers for permutations of essentially the same data.