25
SepIn ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.
Key Points about ViewModel
ViewModel contain fields that are represented in the view (for LabelFor,EditorFor,DisplayFor helpers)
ViewModel can have specific validation rules using data annotations or IDataErrorInfo.
ViewModel can have multiple entities or objects from different data models or data source.
ViewModel Example
Designing ViewModel
public class UserLoginViewModel { [Required(ErrorMessage = "Please enter your username")] [Display(Name = "User Name")] [MaxLength(50)] public string UserName { get; set; } [Required(ErrorMessage = "Please enter your password")] [Display(Name = "Password")] [MaxLength(50)] public string Password { get; set; } }
Presenting the viewmodel in the view
@model MyModels.UserLoginViewModel @{ ViewBag.Title = "User Login"; Layout = "~/Views/Shared/_Layout.cshtml"; } @using (Html.BeginForm()) { <div class="editor-label"> @Html.LabelFor(m => m.UserName) </div> <div class="editor-field"> @Html.TextBoxFor(m => m.UserName) @Html.ValidationMessageFor(m => m.UserName) </div> <div class="editor-label"> @Html.LabelFor(m => m.Password) </div> <div class="editor-field"> @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password) </div> <p> <input type="submit" value="Log In" /> </p> </div> }
Working with Action
public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(UserLoginViewModel user) { // To acces data using LINQ DataClassesDataContext mobjentity = new DataClassesDataContext(); if (ModelState.IsValid) { try { var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList(); if (q.Count > 0) { return RedirectToAction("MyAccount"); } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } catch (Exception ex) { } } return View(user); }
Some Tips for using ViewModel
In ViewModel put only those fields/data that you want to display on the view/page.
Since view reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance.
Use a mapper when ViewModel become more complex.
In this way, ViewModel help us to organize and manage data in a strongly-typed view with more flexible way than complex objects like models or ViewBag/ViewData objects.
Summary
In this article I try to expose the ViewModel with example. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.
Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.