开发者

Where to put validation annotations ViewModel or Domain object?

My Question is

As I am passing UserCreateViewModel from my Create Controller that means my Validation(ModelState.IsValid) will work only on UserCreateViewModel if Annotation are defined on it. But I can not define DataAnnotation on each of my ViewModels because that will be alot of work. Instead I want to put it on User domain model. So how do I fix Create method to fix as my Annotation work and mapper too without adding more code to controller.

//My Controller Create Method

[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 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(E开发者_如何学JAVArrorMessage = "Password is required.")]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "{0} is between {1} to {2}")]
        public string Password { get; set; }
    }
}  


Validation should be put at least on the view model because this is what you receive as user input. As far as validation on the model is concerned you could add it as well but as long as you are passing a view model to your POST action (which is exactly what you should do) the validation on the model will be ignored. Of course that's not a problem here because a model is something that might be reused on other applications as well which don't use view models and this way your model is guaranteed to be valid. As far as ASP.NET MVC is concerned this step is not necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜