ASP.NET 服务器控件属性必须是必需的
我有一个带有属性 Path
的自定义 ASP.NET 服务器控件 CustomControl
。
如果未明确指定 Path
,那么我希望抛出异常。
例如,
应该编译,并且
应该抛出异常。
我意识到我可以在 Path 属性的 getter 中执行此操作,但是是否有某些属性需要这样做?
更新
除了在代码隐藏属性的 getter 方法中使用之外,是否有任何机制可以验证属性属性的值?
I have a custom ASP.NET server control CustomControl
with a property attribute Path
.
If the Path
is not explicitly specified, then I want an exception to be thrown.
For example,
<myControls:CustomControl Path="somedirectory/someotherdirectory/somefile.ext" runat="server" />
should compile, and
<myControls:CustomControl runat="server" />
should throw an exception.
I realize I can do this in the getter of the Path
property, but is there some attribute that necessitates this?
Update
Is there any mechanism for validating the values of the property attributes other than using in the getter methods of the code-behind properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在自定义控件的 init 事件中检查这一点,并引发异常。
更新
有;在初始化事件中检查它。在主机(页面或用户控件)初始化事件之后调用控件的初始化。因此,如果它为 null 或为空,您可以抛出异常
You can check this in init event of the custom control, and throw an exception.
Update
There is; Check it in init event. As init of control's called after host's (page or user control) init event. So you can throw an exception if its null or empty
我认为这不应该是编译时检查。
毕竟,属性值可能在 page_load 或类似事件期间在后面的代码中提供。
I don't think this should be a compile time check.
After all, the property value might be supplied in the code behind during page_load or a similiar event.
没有任何属性需要这样做。执行此操作的最佳位置是在 Path 属性的 getter 中。
There is not an attribute that necessitates this. The best place to do this is in the getter of the Path property.
不,没有办法强制页面框架执行此操作。您需要在运行时在代码中执行此操作,如果未提供该值,则引发异常。否则我们永远不会遇到“糟糕,我忘记了 runat=server 部分”错误:)
No, there's no way to force the page framework to do this. You need to do it in your code at runtime and raise an exception if the value wasn't provided. Otherwise we'd never run into the "crap, I forgot the runat=server part" error :)