I have separate model and viewmodel classes. Where viewmodel classes only do UI level validation (refer: Validation: Model or ViewModel).
I can verify on post action in a controller that model (vewmodel) is valid.
The ask:
How do I validate the model (the main entity with data annotations).
I am not developing the viewmodel using model object. Just duplicating the properties and adding all properties possibly required in that particular view.
//Model Class
public class User
{
[Required]
public string Email {get; set;}
[Required]
public DateTime Created {get; set;}
}
//ViewModel Class
public class UserViewModel
{
[Required]
public string Email {get; set;}
[Required]
public string LivesIn {get; set;}
}
//Post action
public ActionResult(UserViewModel uvm)
{
if( ModelState.IsValid)
//means user entered data correctly and is validated
User u = new User() {Email = uvm.Email, Created = DateTime.Now};
//How do I validate "u"?
return View();
}
Should do something like this:
var results = new List<ValidationResult>();
var context = new ValidationContext(u, null, null);
var r = Validator.TryValidateObject(u, context, results);
What I am thinking is adding this validation technique in the base class (of business entity), and verify it when I am mapping from viewmodel class to business entity.
Any suggestions?
1) Use fluent validation on the model that the retrieves information from the user. it is more flexible then data annotation and easier to test.
2) You might want to look into automapper, by using automapper you don’t have to write
x.name = y.name.3) For your database model I would stick to the data-annotations.
Everything below is based on the new information
First and all you should place validation on both location like you did now for the actual model validation this is how I would do it. Disclaimer: this is not the perfect way
First and all update the
UserViewModeltoThen update the action method to
Now for the user model it gets tricky and you have many possible solutions. The solution I came up with (probably not the best) is the following:
Last some unit test to check my own code: