在ASP.net中,最好在ASPX页面中使用服务器控件还是在后面的代码中动态创建它们?

时间:2021-02-08 15:52:52

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.

我通常更喜欢动态地添加控件(如表和通用html控件)到ASPX页面,而不是将它们添加到ASPX页面并动态设置属性。

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?

还是动态地使用通用的html控件比将格式化的html字符串输出到asp:literal更好的做法?

2 个解决方案

#1


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.

将它们保存在.aspx中动态添加它们会导致查看状态问题,并且必须在每个邮件包中添加它们。我在构建用户生成的表单应用程序时遇到了这个问题。我打破了并使用控件可见性属性作为解决方法。如果您的消除视图状态并从您的应用程序回发,这些可能不是您的问题。

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

#2


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.

由于复杂的决策逻辑,最好自己动手进行相当静态的控制布局,其中只有属性需要修改将控件放在ASPX中才会更直接。

#1


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.

将它们保存在.aspx中动态添加它们会导致查看状态问题,并且必须在每个邮件包中添加它们。我在构建用户生成的表单应用程序时遇到了这个问题。我打破了并使用控件可见性属性作为解决方法。如果您的消除视图状态并从您的应用程序回发,这些可能不是您的问题。

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

#2


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.

由于复杂的决策逻辑,最好自己动手进行相当静态的控制布局,其中只有属性需要修改将控件放在ASPX中才会更直接。