In the mvc.tutorial series, we setup a simple ASP.NET MVC project, configured our DbContext for Dependency Injection and today we are going to look at what benefits a ViewModel gives us over creating strongly typed views against our models, which in this case is tied to our ORM (Object Relational Mapper)
My first instinct after creating my controller and index action in the controller, is to add a new strongly typed view.
What's wrong with this? Well, nothing, your model classes aren't really tied to Entity Framework. You have just informed Entity Framework that you would like to use those classes as tables inside of your DbContext.
Since your classes aren't tied to the ORM, what about validation and using the DataAnnotations
This is where I see problems creeping up. For example, let's take a simple registration on a site. You have this User, the user is required to enter a username, password and email address to register. So, what we do is decorate each property with the RequiredAttribute. Now we can go and create a strongly typed view.
/// <summary>
/// User
/// </summary>
public class User
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string EmailAddress { get; set; }
}
This is all fine and dandy, but now, after many lines of registration code, we decide that we need a Sign In View. For a user to sign in, we only require the username and password, what do we do now? If we had to create a strongly typed view from the User now, our Model State will not be valid on form post as the email address is required.
This is where View Models come in handy. What you could do is create a View Model that describes the view. e.g.
/// <summary>
/// Register User View Model
/// </summary>
public class RegisterUserViewModel
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string EmailAddress { get; set; }
}
/// <summary>
/// Sign In User View Model
/// </summary>
public class SignInUserViewModel
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}
You can still use the Data Annotations and your views will only get the data that they require.
The following article, describes how to map data from a Model to a View Model AutoMapper
Read More

