Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding ViewModel in ASP.NET MVC

Understanding ViewModel in ASP.NET MVC

04 Apr 2024
Intermediate
272K Views
5 min read
Learn with an interactive course and practical hands-on labs

ASP.NET MVC with Web API Foundations Course - Free

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.

What is a 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

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

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

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)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this