开发者

Is applying default values to properties good or bad practice?

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, SortDirectio开发者_JAVA百科n and PageSize. When the page first loads, these need to be set to something.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜