3
我的問題是何處放置驗證註釋ViewModel或Domain對象?
當我從我的創建控制器,這意味着我的驗證(ModelState.IsValid)將於UserCreateViewModel只工作 如果註釋是在它定義傳遞UserCreateViewModel。但是我無法在每個ViewModel上定義DataAnnotation,因爲這很有用。 相反,我想把它放在用戶域模型上。那麼,如何修復Create方法以作爲我的Annotation工作和映射器修復,而無需向控制器添加更多代碼。
//我的控制器創建方法
[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 - >創建特定視圖模型
public class UserCreateViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
//用戶 - >域對象
[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; }
}
}