开发者

Adding and Removing Data Annotations from code

Is there away to add and remove DataAnnotations, in particular the [requried], from the code开发者_Go百科 side of things? My problem is that I want to give the user the ability to save an incomplete form in our CRUD applications but at the same time use the power of the DataAnnotations validation.

If this is not possible, what is the best way I can go about this?


You can keep the DataAnnotation attributes on your model and then just manually clear the validation errors as needed from code. It might look something like this:

if (certainCondition == true) {
   ModelState["someKey"].Errors.Clear();
   ModelState["anotherKey"].Errors.Clear();
}


It is impossible to add, remove or modify DataAnnotations dynamically since they are Attributes. Attributes are part of the type and can't be changed during runtime.

You could use ModelState as Larsenal suggested provided that:

  • you use it After validation has executed. (prior to that, ModelState will be empty. It doesn't provide access to all validators, it only stores validator-errors after they've occurred)
  • you don't have any clientside validation that's based on the DataAnnotationValidators and fires errors that prevent you from even reaching the serverside validation.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜