Prefer To Use ViewModel In ASP.NET MVC

ViewModel is used to encapsulate the multiple entities into single entity. It is basically a combination of data models into single object and rendering by the view.

Sometimes it is required to show the multiple entities data on view which is coming from different data model classes. So, it includes all the data into single one and makes it flexible to show on View in ASP.NET. So, basically it is separation of concerns, it means you include different entities for particular purpose and make main focus on the code.

There are many reasons to use ViewModel:

  1. We can create master detail records for the view.
  2. Create real data with paging information in same group.
  3. Dashboards which includes different source of data.
  4. Aggregate the data for reporting.
  5. Optimized for rendering on the view.

use ViewModel

When to use ViewModel

As per requirement, you need to pass more than one entity to strongly typed view which is best practice then you need to use ViewModel. It is a separate class as an entity. It makes formation and interaction between model and view more easy and simple.

So, if you already have created model entity and want to add some additional  information to show on view then it is best practice to use ViewModel.

ViewModel

Domain Models

Post.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ComponentModel.DataAnnotations;  
  6. using System.ComponentModel.DataAnnotations.Schema;  
  7.   
  8. namespace DotnetTutorial.Data.Entities  
  9. {  
  10.     public class Post  
  11.     {  
  12.         [Key]  
  13.         public int PostId { getset; }  
  14.   
  15.         [MaxLength(500)]  
  16.         [Column(TypeName = "varchar")]  
  17.         public string PostTitle { getset; }  
  18.   
  19.         [MaxLength(1000)]  
  20.         [Column(TypeName = "text")]  
  21.         public string  ShortPostContent { getset; }  
  22.   
  23.         [Column(TypeName="text")]  
  24.         public string FullPostContent { getset; }  
  25.   
  26.         [MaxLength(255)]  
  27.         public string MetaKeywords { getset; }  
  28.   
  29.         [MaxLength(500)]  
  30.         public string MetaDescription { getset; }  
  31.         public DateTime PostAddedDate { getset; }  
  32.         public DateTime PostUpdatedDate { getset; }  
  33.         public bool IsCommented { getset; }  
  34.         public bool IsShared { getset; }  
  35.         public bool IsPrivate { getset; }  
  36.         public int NumberOfViews { getset; }  
  37.         public int EntityType { getset; } /* 1-Posts, 2-Page*/  
  38.           
  39.           
  40.         public virtual int CategoryId { getset; }  
  41.   
  42.         [ForeignKey("CategoryId")]  
  43.         public virtual Category Categories { getset; }  
  44.   
  45.         public int NumberOfLikes { getset; }  
  46.   
  47.         public int NumberOfComments { getset; }  
  48.     }  
  49. }  
Category.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ComponentModel.DataAnnotations;  
  6. using System.ComponentModel.DataAnnotations.Schema;  
  7.   
  8. namespace DotnetTutorial.Data.Entities  
  9. {  
  10.     public class Category  
  11.     {  
  12.         [Key]  
  13.         [Required(ErrorMessage="Category is required")]  
  14.         public int CategoryId { getset; }  
  15.   
  16.         [MaxLength(25)]  
  17.         public string CategoryName { getset; }  
  18.   
  19.         [MaxLength(25)]  
  20.         public string CategorySlug { getset; }  
  21.   
  22.         [MaxLength(1000)]  
  23.         public string CategoryImage { getset; }  
  24.   
  25.         public List<Post> Posts { getset; }  
  26.     }  
  27. }  
Explorer

Now I am going to create a ViewModel which will contain the list of properties which will show on View.

PostViewModel.cs
  1. using DotnetTutorial.Data.Entities;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace DotnetTutorial.Data.ViewModel  
  10. {  
  11.     public class PostViewModel  
  12.     {  
  13.         public PostViewModel()  
  14.         {  
  15.               
  16.         }  
  17.         public int PostId { getset; }  
  18.   
  19.         [Display(Name="Post Title")]  
  20.         [Required(ErrorMessage="Post Title is required")]  
  21.         [RegularExpression(@"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]  
  22.         [StringLength(500,MinimumLength=3, ErrorMessage="Invalid Title Lenght")]  
  23.         public string PostTitle { getset; }  
  24.   
  25.   
  26.         [MaxLength(Int32.MaxValue, ErrorMessage = "More than max value")]  
  27.         [AllowHtml]          
  28.         [Display(Name = "Short Content")]  
  29.         [Required(ErrorMessage = "Short Content is required")]          
  30.         public string ShortPostContent { getset; }  
  31.   
  32.         [AllowHtml]  
  33.         [MaxLength(Int32.MaxValue, ErrorMessage = "More than max value")]  
  34.         [Display(Name = "Full Content")]  
  35.         [Required(ErrorMessage = "Full Content is required")]      
  36.         public string FullPostContent { getset; }  
  37.   
  38.         [Display(Name = "Meta keywords")]  
  39.         //[Required(ErrorMessage = "Meta Keywords is required")]      
  40.         public string MetaKeywords { getset; }  
  41.   
  42.         [Display(Name = "Meta Description")]  
  43.         //[Required(ErrorMessage = "Meta Description is required")]      
  44.         public string MetaDescription { getset; }  
  45.      
  46.         public DateTime PostAddedDate { getset; }  
  47.         public DateTime PostUpdatedDate { getset; }  
  48.         public string TimeAgo { getset; }  
  49.         public bool IsCommented { getset; }  
  50.         public bool IsShared { getset; }  
  51.         public bool IsPrivate { getset; }  
  52.         public int NumberOfViews { getset; }  
  53.         public int EntityType { getset; } /* 1-Posts, 2-Page*/  
  54.         public string ThumbImagePath { getset; }  
  55.         public string ImagePath { getset; }  
  56.   
  57.         [Required(ErrorMessage="Category is required")]  
  58.         public int SelectValue  
  59.         {  
  60.             get;  
  61.             set;  
  62.               
  63.         }  
  64.         public virtual Category postCategory { getset; }  
  65.   
  66.         [Display(Name="Post Category")]          
  67.           
  68.         public virtual List<Category> PostCategories { getset; }  
  69.   
  70.         //[HiddenInput(DisplayValue = false)]  
  71.         [Required(ErrorMessage="Tag is required")]  
  72.         public string hdnTagList { getset; }  
  73.   
  74.         public virtual int CategoryId { getset; }  
  75.         
  76.   
  77.         public string PostYear  
  78.         {  
  79.             get  
  80.             {  
  81.                 return PostAddedDate.Year.ToString();  
  82.             }  
  83.         }  
  84.   
  85.         public string PostMonth  
  86.         {  
  87.             get  
  88.             {  
  89.                 return PostAddedDate.Month.ToString();  
  90.             }  
  91.         }  
  92.   
  93.         //[Required(ErrorMessage="Post url is required")]  
  94.         public string PostUrl { getset; }  
  95.   
  96.         public User userDetails { getset; }  
  97.   
  98.         public int NumberOfLikes { getset; }  
  99.   
  100.         public int NumberOfComments { getset; }  
  101.   
  102.         public int postPageStatus { getset; }  
  103.   
  104.         public string CategoryName { getset; }  
  105.   
  106.         public bool NextPostValid { getset; }  
  107.         public SinglePostPager NextPost { getset; }  
  108.         public bool PreviousPostValid { getset; }  
  109.         public SinglePostPager PreviousPost { getset; }  
  110.   
  111.         public CommentsViewModel comments { getset; }  
  112.           
  113.   
  114.     }  
  115. }  
ArticleController.cs

See the following code where we are using ViewModel to show the data on View.
  1. public ActionResult Index(int? page)          
  2. {  
  3.     AddNewVisitorEntry("Home");  
  4.     var pgNumber = page ?? 1;  
  5.     var pageSize = _settingRepository.PostPerPages;  
  6.     var allPostList = _postRepository.GetPostForHomePage(pgNumber, pageSize);  
  7.     var totalPage = PostExtensions.GetPageCount(_postRepository.GetPostCount(), pageSize);  
  8.     IEnumerable<PostViewModel> model = null;  
  9.     var postEntities = allPostList.Select(x => new PostViewModel()  
  10.     {  
  11.         PostId = x.PostId,  
  12.         PostTitle = x.PostTitle,  
  13.         ShortPostContent = x.ShortPostContent,  
  14.         FullPostContent = x.FullPostContent,  
  15.         MetaKeywords = x.MetaKeywords,  
  16.         MetaDescription = x.MetaDescription,  
  17.         PostAddedDate = x.PostAddedDate,  
  18.         PostUpdatedDate = x.PostUpdatedDate,  
  19.         TimeAgo = x.PostAddedDate.TimeAgo().ToString(),  
  20.         IsCommented = x.IsCommented,  
  21.         IsShared = x.IsShared,  
  22.         IsPrivate = x.IsPrivate,  
  23.         NumberOfViews = x.NumberOfViews,  
  24.         EntityType = x.EntityType,  
  25.         PostUrl = x.PostUrl,  
  26.         ThumbImagePath = x.ThumbImagePath,  
  27.         ImagePath = x.ImagePath,  
  28.         CategoryId = x.CategoryId,  
  29.         postCategory = x.Categories,  
  30.         PostTags = _tagRepository.GetTagListByPostId(x.PostId),  
  31.         userDetails = _userRepository.GetUserDetailsByUserId(x.UserId),  
  32.         NumberOfLikes = x.NumberOfLikes,  
  33.         NumberOfComments = x.NumberOfComments  
  34.     });  
  35.     model = postEntities;  
  36.     ViewBag.TotalPages = Convert.ToInt32(totalPage);  
  37.     ViewBag.CurrentPage = pgNumber;  
  38.     ViewBag.PageSize = pageSize;  
  39.     return View("Index",model);  
  40. }  
View
  1. @model DotnetTutorial.Data.ViewModel.PostViewModel  
  2. @{  
  3.     var userId = 0;  
  4.     if (LoggedUserDetails != null)  
  5.     {  
  6.         userId = LoggedUserDetails.UserId;  
  7.     }  
  8.     var url = Url.RouteUrl("IndividualArticlesPost"new { categoryslug = Model.postCategory.CategorySlug, url = Model.PostUrl });  
  9.     var shareUrl = "http://www.dotnet-tutorial.com" + url;  
  10.     var uniquid = "post123" + Model.PostId;  
  11.     var showReadMore = string.Empty;  
  12.     var content = string.Empty;  
  13.     if (Model.postPageStatus > 0)  
  14.     {  
  15.         content = Model.ShortPostContent;  
  16.         showReadMore = "Yes";  
  17.     }  
  18.     else  
  19.     {  
  20.         content = Model.FullPostContent;  
  21.     }  
  22.     var firstName = Model.userDetails.FirstName;  
  23.     var lastName = Model.userDetails.LastName;  
  24.     var fullName = firstName + " " + lastName;  
  25. }  
  26. <style>  
  27.     #mypost {         
  28.         border: 1px solid #d5d3d3;  
  29.         padding:0 6px 10px 6px;  
  30.     }  
  31. </style>  
  32. <div id="mypost">  
  33.     <div>  
  34.         <h3>  
  35.             <span itemprop="name"> @Html.RouteLink(Model.PostTitle, "IndividualArticlesPost"new { categoryslug = Model.postCategory.CategorySlug, url = Model.PostUrl }, new { @class = "title", @style = "color:#069; font-weight:bold;" })</span>  
  36.         </h3>  
  37.         <div>  
  38.             <b>By : </b> <a class="PostAuthor" href="http://dotnet-tutorial.com/mukeshkumar" itemprop="url">  
  39.                 <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">@fullName</span></span>  
  40.             </a>  
  41.             <b>   Posted On </b><time itemprop="datePublished">@Model.TimeAgo</time>  
  42.         </div>  
  43.   
  44.         <input type="hidden" id="hdnPostId" value="@Model.PostId" />  
  45.     </div>  
  46.     <span itemprop="articleBody">  
  47.         <div>  
  48.             @Html.Raw(content)  
  49.         </div>  
  50.     </span>  
  51.     <div>  
  52.         @if (showReadMore == "Yes")  
  53.         {  
  54.             var postUrl = "http://www.dotnet-tutorial.com" + url;  
  55.             var posttitle = Model.PostTitle;  
  56.             <div class="pull-right">  
  57.                 <a href="@url" class="btn btn-primary" type="button" style="float:right">Read more</a>  
  58.             </div>  
  59.             <br />              
  60.         }  
  61.     </div>  
  62.     <br />  
  63. </div>  
Hope this article will help you to understand the use of ViewModel using above example and how to implement it with ASP.NET MVC project. Thanks for reading this article, hope you enjoyed it.

Up Next
    Ebook Download
    View all
    Learn
    View all