Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should WepApi controller return viewmodels

The WebApi is suited well for Single Page Apps which use javascript ViewModel with KnockoutJS.

Should my WebApi return a c# ViewModel which gets converted to a Json ViewModel then.

Or should my WebApi controller return a business object and create a javascript viewmodel?

I have never seen the first in any WebApi tutorial and I wonder why.

like image 333
Elisabeth Avatar asked Feb 16 '13 15:02

Elisabeth


1 Answers

Should my WebApi return a c# ViewModel which gets converted to a Json ViewModel then

Yes absolutely. This way you have total control over what gets sent to the client. Also if you decide to change your underlying business models in a new version of your API for example you will not break your existing clients. All you need to do is adapt the mapping between your business models and your view models.

Or should my WebApi controller return a business object and create a javascript viewmodel?

No, never sent your business models to a client. You should always use view models.

I have never seen the first in any WebApi tutorial and I wonder why.

I have never seen the first in any ASP.NET MVC tutorial neither, and me too I wonder why. Probably because the tutorials are not covering real world application scenarios but represent oversimplified examples that would allow you to get started with some technology. It's unfortunate because so many people follow those tutorials without realizing the importance of using view models in real world applications. StackOverflow is a great place to see how many people are actually not aware of the importance of view models.

like image 179
Darin Dimitrov Avatar answered Oct 16 '22 14:10

Darin Dimitrov