21
NovUnderstanding ViewModel in ASP.NET MVC
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.
Key Points about ViewModel
ViewModel contains 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 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
In ViewModel put only those fields/data that you want to display on the view/page.
Since view represents the properties of the ViewModel, hence it is easy to render and maintain.
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.