Where and how to check and display ViewModel?

I am trying to learn Domain Driven Design and recently read that many people are in favor of creating ViewModels for your views, which store all the values โ€‹โ€‹that you want to display in this view.

My question is, how should I perform form validation? Should I create separate validation classes for each view or group them together? I am also confused about how this will look in code.

This is how I now think that validation and viewmodels fit into the scheme of things:

View (some user input) -> Controller -> FormValidation (from ViewModel) -> (If a valid map is for ViewModel model for a domain) -> Domain-level service -> Infrastructure

Thanks!

PS I am using Asp.net MVC with C #

+6
validation asp.net-mvc viewmodel domain-driven-design
source share
4 answers

I experimented with placing my form validation in the ViewModel, and I use the service level for complex validation of the business.

This works really well, and the code is much easier to read and maintain.

0
source share

I suggest you introduce your validation rules into your domain model. This is the easiest and most repetitive way (for example, use System.ComponentModel.DataAnnotations - the MVC-compatible standard MVC 2 middleware supports it out of the box).
If you have a complex and large-scale domain model and you donโ€™t get hung up on matching properties with the same name, try using AutoMapper, which is a great tool for doing this kind of work.

0
source share

Confirm presentation model at presentation level. Keep in mind that you should only check the validation associated with the presentation (date in the correct format, name! = "" Etc.).

Asp.net Mvc has built-in validation support , which is usually sufficient for basic validation.

The tricky part about applying a domain-driven architecture is domain validation. There can be complex rules, depending on repositories and similar materials, which could do a โ€œvalidationโ€ without making the dumb domain model quite difficult.

Therefore, it seems like a good idea to never allow a domain object to slide into invalid state and just throw an exception in case this happens.


Itโ€™s better not to try to mechanically map the model of the model to the domain model - this approach increases the connection, can disrupt the encapsulation of your domain model and omit it.

0
source share

This is a general question, and it does not always have the correct answer. Give up this post from Derick Bailey. This is a good discussion on this subject and has several links to some other great posts on this subject.

0
source share

All Articles