Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Browse Tutorials

02 Intermediate

Understanding ViewModel in ASP.NET MVC

Understanding ViewModel in ASP.NET MVC

05 Mar 2024
Intermediate
266K Views
5 min read

ViewModel in ASP.NET MVC: An Overview

In this article, We will see ViewModel in ASP.NET MVC Application with an example.In thisMVCtutorial, ViewModel is a class that contains the fields that are represented in the strongly typed view. It is used to pass data from the controller to a strongly typed view.

What is a ViewModel in ASP.NET MVC?

A single model object in an MVC application could not include all the information needed for a view. For that, A view could need distinct model data, for instance. To overcome this drawback ViewModel is needed. ViewModel is a model that includes many model data needed for a specific view. In ASP.NET MVC, we refer to this model as ViewModel since it is dedicated to a single view.

Let's See the actual visual representation of a ViewModel in the MVC application.

 ViewModel in ASP.NET MVC

Key Points about ViewModel

  1. ViewModel contains 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 sources.

ViewModel Example


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

  1. In ViewModel put only those fields/data that you want to display on the view/page.

  2. Since view represents the properties of the ViewModel, hence it is easy to render and maintain.

  3. Use a mapper when ViewModel becomes more complex.

In this way, ViewModel helps us to organize and manage data in a strongly typed view in a more flexible way than complex objects like models or ViewBag/ViewData objects.

Summary

In this article, I tried to expose the ViewModel with an example in MVC. I hope you will refer to this article for your needs. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article.

Unlock the next level of MVC:

FAQs

Q1. What does a ViewModel do?

To acquire and keep the information that is necessary for an Activity or a Fragment.

Q2. What is the ViewModel in asp?

 It is used to shape multiple entities from one or more models into a single object.

Q3. Why is ViewModel needed?

It is responsible for holding and processing all the data needed for the UI.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this