asp.net mvc - What's the recommended place to perform validation: ViewModel, Model or Controller? -
i have registration page , perform validation (in addition stringlength , required annotations on viewmodel) duplicate usernames , email addresses. perform validation in controller when registration form posted back. i'm not sure if right place though.
i can't imagine viewmodel right place require viewmodel have reference userrepository. make sense have kind of validation in model classes?
if so, how implement on model can check if information valid before sent repository?
update
code of controller action:
if (modelstate.isvalid) { if (!_userrepository.exists(registerviewmodel.username)) { if (!_userrepository.emailexists(registerviewmodel.email)) { _userrepository.add( new user { created = datetime.now, email = registerviewmodel.email, password = registerviewmodel.password, username = registerviewmodel.username }); _userrepository.savechanges(); tempdata["registrationdetails"] = registerviewmodel; return redirecttoaction("confirm"); } else { modelstate.addmodelerror(string.empty, "this email address in use."); } } else { modelstate.addmodelerror(string.empty, "this username taken."); } } return view(registerviewmodel); }
update 2
should domain model care such constraints duplicate user names or email addresses or controller layer should worry about?
update 3
it seems putting validation logic in controller makes sense can reused in remote validation , in model validation on submit. checking duplicates thing should done in controllers or make sense have these kind of checks in domain model?
thanks,
i suggest in controllers.
the main reason whatever structure of app be, need use ajax notify user whether username has been taken or not. otherwise it's bad usability doesn't justify code structure.
and have action method ajax-ly see if username exists or not.
overall, mean may end 2 sets of validation method (ui , model) cause.
also make usable site using javascript framework knockoutjs or backbone. thats true mvvm , in case having viewmodels being model layer classes (as chris mentioned) not idea. you'll end 2 sets of validation anyways.
Comments
Post a Comment