views:

62

answers:

3

Is it good or bad practice to apply System.ComponentModel.DefaultValue default values to my properties? What about my ViewModel properties?

I ask because I'm passing a ViewModel into my Controller. This ViewModel contains properties such as OrderByColumn, SortDirection and PageSize. When the page first loads, these need to be set to something.

A: 

First off DefaultValue does nothing by itself and you'll have to invoke the default values via reflection. A better thing to do is use the ViewModels constructor to set these default values.

As far as default values go, sometimes null doesn't cut it, and you need to have them. This is totally dependent on your requirements though.

jfar
+1  A: 

If you are comfortable setting these values in your ViewModel then it should be ok. I do this for setting SelectLists that are tied to Enumerations on my view. As long as these are defaults for the particular View. If these are more wide sweeping I would suggest building some kind of convention to set them inside your controller.

Khalid Abuhakmeh
+1  A: 

System.ComponentModel.DefaultValue does not help you in that case. It is designed to set only default values for properties in designer.

Check this: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

If you need to set default values to your model you have at least two another options:

1) you may set default values in constructor

2) directly in controller, in that case you may check if e.g OrderByColumn == null then assign default value.

bigb