Does it Make Sense to have ViewModels in the Webapi?

asp.net Mvcasp.net Web-Api

asp.net Mvc Problem Overview


I am starting to learn the webapi and find myself doing stuff that makes sense in an MVC project but may not make sense in.

Normally in an MVC project I make ViewModels and use that as the parameter or pass them back with the view.

Since there are no views in webapi I guess it does not make sense to have a ViewModel as parameter.

I am wondering maybe if I should just have as a Parameter my EF domains(code first) and put data annotations on top of these. I normally would put the annotations over the view model properties as I liked this over the domain.

However what is stopping me from doing this is I am not 100% clear how my MVC site would work.

Does the MVC site just spit back simples views and then you use Jquery to call your webapi or do you just call MVC action methods that directly just call the same methods the Webapi would call?

If is the second way then I rather put the data annotations on my view model again but then I am putting the same ones on both the EF domain and VM's and that seem redundant.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

My suggestion after loooong time working with this 'things' :

BindingModels for data binding (mvc or api)

ViewModels for views on mvc (you may have some mvc pages inside your api, so it's good to have a place for this, this can be documentation, intro page, whatever. If there is none view, then you can have zero ViewModels) One benefit of this is that you can in your Views/web.config have the ViewModels namespace reference and it won't be polluted with your api resources.

ResourceModel for web api resources. In webapi, nested resources are also resources that go anywhere in a tree which is not that common on mvc, so naming them resources make a lot of sense.

If you want to receive a resource, you can use your resource model. Remember your are receiving the same your are sending back.

If you want a custom binding for input (this should be your default scenario) you have your binding models.

If you have any mvc view, for admin purposes, documentation, whatever, use your ViewModels.

If you have a form page on mvc, you can use your BindingModel also on the POST controller. No need to have a different model for a post on MVC or WEBAPI. Specially when model binder or formatter can both understand and map to the same binding model using the same Data Annotations.

Sometimes, you want to create a binding model with a resource and some extra fields. Inheritance is your friend.

Sometimes you want to create binding model with more than one resource and (optionally, extra fields) Resources as properties are your friend.

In MVC world, you can also use the concept of 'Resource' but it is much less common. This come in handy when you have MVC and Web Api on the same project.

If you need further comments on any item (like folder structure, namespaces, etc), just let me know. I'm more than happy to share my cons pros experience.

Oh, and I forgot, a mapping strategy is worth research. I personally do my own mappings, but having this logic in one place is priceless.

EDIT: Very naive example

ContactViewModel{

    string Name {get;}
    string LastName {get;}
    List<Country> AvailableCountries {get;}
    Country Country {get;}
    bool IsAdmin {get;}

}

ContactBindingModel{

    string Name {get;set;}
    string LastName {get;set;}
    int Country {get;set;}

}

ContactResourceModel{

    string Name { get;set;}
    string LastName {get;set;}
    Country Country {get;set;}
    string IsAdmin {get;}

}

Solution 2 - asp.net Mvc

Terminology aside, having models for binding to is still of use. They just aren't technically ViewModels anymore, in that you're right there are no views involved. But they are definitely still of use. Using them allows you to take advantage of attributes on your Model's properties and allows you to reuse them across your API if needed. Also remember if you use your entities directly WebAPI will model bind all parameters to them that match by name, even if you didn't mean to.

Also, the Entity Models are representations of your raw data, but the Models used for binding against are a fixed contract that the API requests need to satisfy to successfully process a request. The values in which, could end up spanning multiple entity models by the time your implementation is done, and not be persisted to a data store at all.

Solution 3 - asp.net Mvc

If you are trying to build a REST based system then the notion of ViewModel and View can be very useful. You can fairly closely map the notion of Resource to ViewModel and representation to View.

If you stop to think for a moment about what a view looks like in an MVC site. It's a HTML document. A document that contains a bunch of semantic information, title, body, sections, paragraphs, tables, etc. It's not supposed to contain "style" information. That's the job of the web browser and CSS. People get confused when they start to think of HTML as UI. It's not supposed to be UI, it is the content of the UI.

Views are just a concrete realization of the view model content using some media type that can be transferred over the wire. What that media type is, depends on what client you are trying to satisfy.

Solution 4 - asp.net Mvc

We are currently working on a similar project that uses ASP.Net MVC and ASP.Net Web Api.

We use ASP.Net MVC to generate the global structure of our pages. Then, our MVVM javascript implementation calls the web api to fill returned data in client view models. To do that, our api returns view model that correspond to what the front end is waiting for.

I think that your api view models would differ from MVC ViewModels (that are not ViewModels from a MVVM point of view).

It depends on your use of api too. For example, for an internal use, you don't always need to avoid to show your domain model. So you will avoid to map the Model in the ViewModel and increase performances. But in the case you need to transform some properties in your models, viewModels will greatly help you to structure your code in a loosely coupled way.

> Since there are no views in webapi I guess it does not make sense to have a ViewModel as parameter.

I would say your api is consumed by your views in the end, it makes sense to have ViewModel.

> Does the MVC site just spit back simples views and then you use Jquery to call your webapi or do you just call MVC action methods that directly just call the same methods the Webapi would call?

It is just a question of choice here. You can call MVC action to receive generated views (in html) or you can call WebApi to receive JSON/XML responses that you will then bind with your javascript code in your views.

Solution 5 - asp.net Mvc

Just to add what others have said, the use of what would normally be termed a ViewModel is useful for validation as well. You can mark up your classes with data annotations including any validation requirements. In your controller actions you can still use ModelState to force the validation to occur and return appropriate messages via HttpRequestException or just HttpResponseMessage.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionchobo2View Question on Stackoverflow
Solution 1 - asp.net MvcBart CalixtoView Answer on Stackoverflow
Solution 2 - asp.net MvcNick AlbrechtView Answer on Stackoverflow
Solution 3 - asp.net MvcDarrel MillerView Answer on Stackoverflow
Solution 4 - asp.net MvcJulienView Answer on Stackoverflow
Solution 5 - asp.net MvcJacob RutherfordView Answer on Stackoverflow