What’s the best way to validate a model when using mvc with repository?
I look for examples but I didn’t find any that is exactly what I need.
Assuming I have a model with 5 properties.. 3 of them with dataannotations.. and I have some validations that I need to check in database before insert.
I need something like ‘User.IsValidToInsert’ to check if its valid. But I want to use ‘ModelState.IsValid’ too, cause I dont want to check manually all properties with dataannotations in ‘IsValidToInsert’.
How can I do this? Should I set validations that access database in ‘IsValidToInsert’? Should I pass ‘User’ and ‘ModelState’ like parameters to repository class?
You should be using a View Model that is specific to the view. If you have a
Createaction to create aProduct, create aProductCreateview model. You can put the data annotations (or Fluent Validation, etc.) that is specific to creating a product. This will be the model for your View/Controller. If you have an Edit page, then create aProductEditview model.Now if you have additional logic (such as validating if a user already exists, then you should put that in a service layer. Your controller should be as simple as possible. You post your view model, convert it to a domain model and pass it to the service layer if necessary.