在 CompositeControl 中保留由视图状态支持的集合
也许这是漫长的一天,但我在将 ASP.NET ViewState 支持的集合保留在 CompositeControl 中时遇到了麻烦。这是一个简化版本:
public class MyControl : CompositeControl
{
public Collection<MyObject> MyObjectCollection
{
get {
return (Collection<MyObject>)ViewState["coll"] == null ?
new Collection<MyObject>()
: (Collection<MyObject>)ViewState["coll"];
}
set { ViewState["coll"] = value; }
}
}
public partial class TestPage : System.Web.UI.Page
{
protected void btn_Click(object sender, EventArgs e)
{
myControl1.MyObjectCollection.Add(new MyObject());
}
}
单击按钮时,事件处理程序 btn_Click 执行正常,但 MyObjectCollection 的 setter 永远不会被调用,因此 new MyObject() 永远不会被持久化。
我想我只是在享受金发时刻。有人愿意帮忙吗?
Maybe it's been a long day but I'm having trouble persisting a collection backed by the ASP.NET ViewState in a CompositeControl. Here's a simplified version:
public class MyControl : CompositeControl
{
public Collection<MyObject> MyObjectCollection
{
get {
return (Collection<MyObject>)ViewState["coll"] == null ?
new Collection<MyObject>()
: (Collection<MyObject>)ViewState["coll"];
}
set { ViewState["coll"] = value; }
}
}
public partial class TestPage : System.Web.UI.Page
{
protected void btn_Click(object sender, EventArgs e)
{
myControl1.MyObjectCollection.Add(new MyObject());
}
}
When the button is clicked, the event hander btn_Click executes fine, but the setter for MyObjectCollection never gets called, hence the new MyObject() never gets persisted.
I think I'm just having a blonde moment. Anyone fancy helping out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对集合调用
Add()
与对MyObjectCollection
属性调用 setter 不同。正是由于这个原因,像 FxCop 这样的工具建议您不要在 Collection 属性上设置 setter - 要么将 setter 设置为私有,要么将其完全删除。
您可能需要实现自己的集合类型并重写 Add 和 Remove 方法,以便在调用它们时执行持久性代码。
Calling
Add()
on your collection isn't the same as calling the setter on theMyObjectCollection
property.It's for this reason that tools like FxCop suggest that you don't have setters on Collection properties - either make the setter private or remove it completely.
You may need to implement your own collection type and override the Add and Remove methods, such that when they are called, the persistence code is executed.