简体   繁体   中英

Required for model but initially empty field for View - MVVM

please help me with this:

I have model with property of Enum type. This property is required, but on View initial value must be empty. Will show watermark..

If I understand correct than model will have not nullable property. But viewModel will have nullable. Is this right way?

Looks like in this case:

  • need create viewModel
  • viewModel and model will have different data sometimes
  • viewModel need logic for set and get correct values to/from model or get null in first time and leave as is model
  • viewModel need one more validation rule

Other way is:

Model will have nullable property and required validation:

  • can bind to model
  • model does not "correspond to reality"
  • we need always expose data from nullable enum and forgot about null? or handle it (convert to DTO or something like this)
  • nullable property is only UI requirement and can be changed in future

Having the (domain) model use a non-nullable enum suggest that the value MUST have a valid value for use case and / or data integrity.

Having the requirement on the UI to allow a non-valid value (initial or otherwise) will result in 1 of 2 things:

When the View posts a null value (via a dedicated ViewModel) and checks are performed to ensure its not null (I assume that the user selects the "Please Select" value from a select box) the server will respond with an error message saying something like "Please select a valid value blah blah". Or, the server will allow the null from the View Model and default the domain model property to some predetermined sensible value.

In my experience this kind of setup leads to a frustrating user experience because having the UI present an invalid selection option that only feedsback upon submit (or using some frontend / client validation) is rather annoying (especially on a long form, Etc).

Perhaps you would be better rethinking that requirement so the UI only presents valid enum values for selection and optionally make the default one a sensible value.

Having said that if you really want the UI to not have a valid initial value then make a view model with a nullable version and validate on the server as you suggest. As far as changing the (domain) model with a nullable, you already seem concerned that it doesn't "correspond to reality" which is a good impulse considering you already mentioned that this is a UI only requirement, thus place the detail in that layer and keep your domain modals as close to reality as is needed to satisfy your use cases and / or business requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM