I was writing up a controller action that creates a new user. Currently, the controller action takes in the user entity model as a parameter.
I was wondering if I should pass values from the front-end in its own view model, and then extract values and create the entity in the backend?
public ActionResult AddUser(User user)
{
context.Users.Add(user);
context.SaveChanges();
}
vs
public ActionResult AddUser(UserViewModel userViewModel)
{
var user = new User(userViewModel.Name);
context.User.Add(user);
context.SaveChanges();
}
Thanks!
As with most things, there are multiple ways to do it. Ultimately in this case it often comes down to personal preference.
When I’m doing this same thing, I often ask myself if what’s being passed into the method is actually a valid
Userat all. I like to keep my models in such a way that they internally prevent invalid states, rather than rely on the calling code to maintain validity of the model.As such, sometimes there are actions which receive information which describes a model but doesn’t fully construct a model by itself. In these cases, I prefer to use a view model. This often leads me to use view models across the board if for no other reason than consistency.
It particularly comes in handy if I need information from more than one model on the page. Having a view model that’s a composite of the information I need rather than something like a
Tupleof two models just feels cleaner to me. This also allows me to add additional properties to the view model (calculated fields, flags, etc.) that are useful to the view but would pollute the business object. (Switches to show/hide certain form elements, validation items, etc.)Often times you can find your own preference to this sort of question by noting the difference between an object (
User) and a data structure (UserViewModel). In a traditional object-oriented sense, theUsershould hide its data members and provide an interface of functionality, whereas a flat data structure likeUserViewModelwould expose its data members and have no meaningful functionality.Since the view is just looking to bind to data members, I usually go with a flat view model instead of a domain object.