views:

66

answers:

2

I generally prefer to add controls dynamically, like table and generic html controls, to the ASPX page, rather than add them in the ASPX page and set the properties dynamically.

Which approach is considered "better practice"?

Also is using generic html controls dynamically a better practice than outputting formatted html strings to an asp:literal?

Cheers!

+1  A: 

Keep them in the .aspx
Adding them dynamically leads to view state issues and they must be added in each post pack. I ran into this when building a user generated forms app. I Broke down and used the controls visibility property as a work around. That said if your eliminating view state and post back from your app these may not be issues for you.

http://aspnet.4guysfromrolla.com/articles/092904-1.aspx

jms
You get view state issues if you 1) don't put add the to the page at correct point in the lifecycle and 2) you use the abomination called view state in the first place ;)
AnthonyWJones
Managing the lifecycle for dynamic controls is a pain, as well. That doesn't mean they aren't useful, but only in moderation.
Dave Swersky
No arguments there. :)
jms
+1  A: 

Since in both approaches you end up with a set of code that adds controls and assigns values to their properties then the best practice is the approach that is the most readable.

Due to complex decision logic it may be better to do it all yourself on the hand for fairly static control layout where only the properties need modifying placing the control in the ASPX would be more straight-forward.

AnthonyWJones