Is it correct way to use ModelState.Remove to deal with ModelState?

后端 未结 5 845
挽巷
挽巷 2020-12-05 14:17

Im working on a big MVC3 web application and have an annoyance regarding the ModelState.IsValid method.

ModelState is being used in nearly all of my con

5条回答
  •  生来不讨喜
    2020-12-05 15:05

    Fundamentally, your issue is that while your classes are decorated with [Required], it's not always true. If you're operating in a context where it isn't true, you should really be using a class that doesn't define the property as being [Required].

    You should really use a ViewModel that is correctly defined for its specific usage and that may mean duplicating some classes. A ViewModel is associated with the implementation of the UI and while it may use classes from your domain model, it's not always the right thing to do.

    Failing that, the options are to either not use ModelState.IsValid, or to continue to use ModelState.Remove.

    But logically, it makes sense for your ViewModel to be 'validatable', not to have to ignore certain validation errors.

提交回复
热议问题