In MVC, what is a ViewModel?

前端 未结 2 358
Happy的楠姐
Happy的楠姐 2020-12-06 04:27

Am I right in thinking it\'s almost like a wrapper for all the objects necessary for a View?

For example, say you had an online store that sold music and dvds. On yo

2条回答
  •  没有蜡笔的小新
    2020-12-06 05:10

    1. ViewModel contain 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 source.

    Designing ViewModel

    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())
    {
    
    @Html.LabelFor(m => m.UserName)
    @Html.TextBoxFor(m => m.UserName) @Html.ValidationMessageFor(m => m.UserName)
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password)

    }

    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);
    } 
    
    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.

提交回复
热议问题