Tuesday, July 26, 2016

Setting a Default Value for a ViewModel using Data Annotations

In some cases, you may want to set a Default Value for an attribute in your ViewModel (or Model).  Of course, you can do this in your class constructor, but it is much easier and cleaner to set these values using Data Annotations!  This is especially true if you are already using Data Annotations to decorate your ViewModels.

You can do this readily using the DefaultValue Data Annotation as documented here: https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.110).aspx

If you do not use a constant value to assign a value for your DefaultValue attribute, you may encounter the following error message:


This is easily remedied though by simply assigning your value to a constant instead of a statically assigned property such as:

Ultimately, this ends up looking like this for your Data Annotation:

No comments:

Post a Comment