My question
How do I pass UserCreateViewModel from my Create Controller, which means that my check (ModelState.IsValid) will only work on UserCreateViewModel if annotations are defined on it. But I cannot define a DataAnnotation for each of my ViewModels, because it will be a lot of work. Instead, I want to place it on a custom domain model. So, how can I fix the Create method to fix both my work with annotation and using mapper without adding more code to the controller.
// My method of creating a controller
[HttpPost]
public ActionResult Create(UserCreateViewModel user)
{
if (ModelState.IsValid)
{
var createUser = new User();
Mapper.Map(user, createUser);
_repository.Add(createUser);
return RedirectToAction("Details", new { id = createUser.UserId });
}
return View("Edit", user);
}
// UserCreateViewModel -> Create a specific view model
public class UserCreateViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
// User → Domain Object
[MetadataType(typeof(User.UserValidation))]
public partial class User
{
private class UserValidation
{
[Required(ErrorMessage = "UserName is required.")]
[StringLength(50, MinimumLength = 2, ErrorMessage = "{0} is between {1} to {2}")]
[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password is required.")]
[StringLength(50, MinimumLength = 2, ErrorMessage = "{0} is between {1} to {2}")]
public string Password { get; set; }
}
}