Click here to Skip to main content
15,889,839 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
How to use View Model in asp.net mvc
Posted
Comments
nagendrathecoder 22-Jan-15 8:10am    
Has google stopped working?

Declare class. Create instances - usually populating lists or individual objects with selection and projection from data model. Pass it to the view from an action, use in the view.
But here are some tutorials if you couldn't find something like them on your own: http://www.dotnet-tricks.com/Tutorial/mvc/QHQT270712-Understanding-ViewModel-in-ASP.NET-MVC.html[^], http://sampathloku.blogspot.fr/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html[^]
 
Share this answer
 
v4
View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:

public class LoginPageVM
{
[Required(ErrorMessage = "Are you really trying to login without entering username?")]
[DisplayName("Username/e-mail")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter password:)")]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Stay logged in when browser is closed")]
public bool RememberMe { get; set; }
}
Using this view model you can define the view (Razor view engine):

@model CamelTrap.Models.ViewModels.LoginPageVM

@using (Html.BeginForm()) {
@Html.EditorFor(m => m);
<input type="submit" value="Save" class="submit" />
}
And actions:

[HttpGet]
public ActionResult LoginPage()
{
return View();
}

[HttpPost]
public ActionResult LoginPage(LoginPageVM model)
{
...code to login user to application...
return View(model);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900