ASP.NET MVC: How do I validate a model wrapped in a ViewModel?
Posted
by Deniz Dogan
on Stack Overflow
See other posts from Stack Overflow
or by Deniz Dogan
Published on 2010-06-15T14:26:29Z
Indexed on
2010/06/15
14:32 UTC
Read the original article
Hit count: 324
For the login page of my website I would like to list the latest news for my site and also display a few fields to let the user log in. So I figured I should make a login view model - I call this LoginVM
.
LoginVM
contains a Login
model for the login fields and a List<NewsItem>
for the news listing.
This is the Login
model:
public class Login
{
[Required(ErrorMessage="Enter a username.")]
[DisplayName("Username")]
public string Username { get; set; }
[Required(ErrorMessage="Enter a password.")]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
}
This is the LoginVM
view model:
public class LoginVM
{
public Login login { get; set; }
public List<NewsItem> newsItems { get; set; }
}
This is where I get stuck. In my login controller, I get passed a LoginVM
.
[HttpPost]
public ActionResult Login(LoginVM model, FormCollection form)
{
if (ModelState.IsValid)
{
// What?
In the code I'm checking whether ModelState
is valid and this would work fine if the view model was actually the Login
model, but now it's LoginVM
which has no validation attributes at all.
How do I make LoginVM
"traverse" through its members to validate them all? Am I doing something fundamentally wrong using ModelState
in this manner?
© Stack Overflow or respective owner