Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The answer to your question is no you should generally separate your domain models from your view models. Consider a following scenario. Let's say you have a User model and your business logic allows you to both add a new user and edit an existing user. Let's say your user model looks like this:</p> <pre><code>public class User { [Required] public int? UserId {get; set;} [Required] public string LastName {get; set;} [Required] public string FirstName {get; set;} [Required] public string Password {get; set;} public bool IsAdmin {get; set;} } </code></pre> <p>Now in order for your user model to be valid you have to have User ID to make the user identifiable. When you're inserting a new user you don't need the ID because that is something database will automatically take care of on insertion. However when you're doing an update of the user then you need the user ID to be populated. So now you have a model that in one case requires a field (UserId) but in another it doesn't. How are you going to handle that?</p> <p>The answer is view models and this is the reason why they exist and why it's advised to create one for each entry form you have in your project. In this case you would end up with a different insert and update user view models. I know it's tedious to convert these view models into the underlying domain models but there are libraries to help you do that automatically like AutoMapper (<a href="https://github.com/AutoMapper/AutoMapper/wiki/Getting-started" rel="nofollow">https://github.com/AutoMapper/AutoMapper/wiki/Getting-started</a>).</p> <p>2nd and probably more serious problem is over posting. Suppose you are using the above User model to edit the user in your database. Now the model has an IsAdmin field which specifies whether user is an admin or not. Now your edit user view will omit this field since you don't want the general user to be able to make themselves an admin. But let's say you're dealing with a really smart user and he make a hidden field with id of IsAdmin and makes it value to be true:</p> <pre><code> &lt;input type="hidden" id="IsAdmin" value="true" /&gt; </code></pre> <p>and then he/she posts the form to your save user url. Because you are using the domain logic user model which has IsAdmin property this hidden field will map to your model and this user just managed to make himself/herself and admin in your site. This is precisely why you need view models so this scenario can never happen.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload