asp.net MVC should a View-Model Encapsulate Domain

2019-02-17 13:18发布

问题:

I've see a lot of MVC examples where domain-objects are passed directly to views, this will work fine if your view is simple.

The common alternative is to have a view-model which has all the same properties as your domain-model + any extra properties your view may need (such as 'confirmPassword').

Before doing too much reading and before discovering AutoMapper I started creating my own variant of view-model where the domain-object (or multiple domain objects) are simply properties of the view-model.

Have I done a bad thing? What problems or benefits could be derived from this approach? Under what circumstances might this way of doing things work well?

回答1:

There's nothing inherently bad about exposing your domain model directly to the view. The primary risk comes from exposing a property you didn't mean to, like a salary field on an Employee object. Be sure to watch out for this if you're returning JSON.

Another thing to watch out for is when you're binding back from an edit form. You should be aware about the specific risks that are involved. Basically a malicious user could add fields to the POST that happen to match fields that you didn't mean to be editable. I always bind to an intermediary object which is passed into a service before mapping it back to the domain.



回答2:

Bad? Can't use Automapper. ;)

Good? Nothing comes to mind.

I don't think you've done anything horrible. Does it work for you? If so then why not?