What is viewmodel in MVC ?

  • View model represents entities which you want to show in view.

Lets take example of table named “User” which has following entities.

public class User
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public DateTime DateCreated { get; set; }
     public string UserName { get; set; }
     public string Password { get; set; }
}

When creating login view for users to login, we only need UserName & Password of the User, So we can create ViewModel for login View like bellow.

public class UserLoginViewModel
{
     public string UserName { get; set; }
     public string Password { get; set; }
}

This can be used in View Like this

@model MyProject.WebUI.ViewModels.UserLoginViewModel

<table>
     <tr>
          <td><b>First Name:</b></td>
          <td>@Html.TextBoxFor(x => x.UserName)
              @Html.ValidationMessageFor(x => x.UserName)
          </td>
     </tr>
     <tr>
          <td><b>Last Name:</b></td>
          <td>@Html.PasswordFor(x => x.Password)
              @Html.ValidationMessageFor(x => x.Password)
          </td>
     </tr>
</table>

Here we can use validations also like bellow.

public class UserLoginViewModel
{
     [Display(Name = "User Name")]
     [Required(ErrorMessage = "User name is required")]
     public string UserName { get; set; }

     [Display(Name = "Password")]
     [Required(ErrorMessage = "Password is required")]
     public string Password { get; set; }
}

Like this we will only show those entities which are necessary for view & not all entities.

admin