Understanding ViewModel in ASP.NET MVC

In 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

  1. ViewModel contain fields that are represented in the view (for LabelFor,EditorFor,DisplayFor helpers)
  2. ViewModel can have specific validation rules using data annotations or IDataErrorInfo.
  3. ViewModel can have multiple entities or objects from different data models or data source.

ViewModel Example

Designing ViewModel

  1. public class UserLoginViewModel
  2. {
  3. [Required(ErrorMessage = "Please enter your username")]
  4. [Display(Name = "User Name")]
  5. [MaxLength(50)]
  6. public string UserName { get; set; }
  7. [Required(ErrorMessage = "Please enter your password")]
  8. [Display(Name = "Password")]
  9. [MaxLength(50)]
  10. public string Password { get; set; }
  11. }

Presenting the viewmodel in the view

  1. @model MyModels.UserLoginViewModel
  2. @{
  3. ViewBag.Title = "User Login";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. @using (Html.BeginForm())
  7. {
  8. <div class="editor-label">
  9. @Html.LabelFor(m => m.UserName)
  10. </div>
  11. <div class="editor-field">
  12. @Html.TextBoxFor(m => m.UserName)
  13. @Html.ValidationMessageFor(m => m.UserName)
  14. </div>
  15. <div class="editor-label">
  16. @Html.LabelFor(m => m.Password)
  17. </div>
  18. <div class="editor-field">
  19. @Html.PasswordFor(m => m.Password)
  20. @Html.ValidationMessageFor(m => m.Password)
  21. </div>
  22. <p>
  23. <input type="submit" value="Log In" />
  24. </p>
  25. </div>
  26. }

Working with Action

  1. public ActionResult Login()
  2. {
  3. return View();
  4. }
  5. [HttpPost]
  6. public ActionResult Login(UserLoginViewModel user)
  7. {
  8. // To acces data using LINQ
  9. DataClassesDataContext mobjentity = new DataClassesDataContext();
  10. if (ModelState.IsValid)
  11. {
  12. try
  13. {
  14. var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();
  15. if (q.Count > 0)
  16. {
  17. return RedirectToAction("MyAccount");
  18. }
  19. else
  20. {
  21. ModelState.AddModelError("", "The user name or password provided is incorrect.");
  22. }
  23. }
  24. catch (Exception ex)
  25. {
  26. }
  27. }
  28. return View(user);
  29. }

Some Tips for using ViewModel

  1. In ViewModel put only those fields/data that you want to display on the view/page.
  2. Since view reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance.
  3. 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.

Do you want more TechChaitu Updates ?
Enter your email address:

Comments

Popular posts from this blog