In ASP.net is it better to use Server Controls within the ASPX page or create them dynamically in the code behind?

StackOverflow https://stackoverflow.com/questions/619588

  •  03-07-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top