Infolink

 

Search This Blog

Oct 21, 2012

When to use ViewModel in mvc3

In asp.net mvc, a controller can pass single object to the corresponding view. This object may be a simple object or a complex object. ViewModel is a complex object that may contain multiple entities or objects from different data models or data source. Basically ViewModel is a class that specify data model used in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Designing the model

public class UserLoginModel
{
[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 model in the view

@model MyModels.UserLoginModel
    @{
    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(UserLoginModel 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 reperesents the properties of the ViewModel, hence it is easy for rendering and maintenance.
  3. Use a mapper when ViewModel become more complex.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...