如何持久化 ListASP.NET 自定义控件中的属性?
我在自定义控件中有以下属性:
List<myClass> _items;
public List<myClass> Items{
get { return _items; }
set { _items= value; }
}
在我的代码隐藏中,我将项目添加到集合中,如下所示...
myCustomControl.items.Add(new myClass());
但是,这些项目不会在回发中保留。 允许自定义控件持久化的正确方法是什么?
I have the following property in a custom control:
List<myClass> _items;
public List<myClass> Items{
get { return _items; }
set { _items= value; }
}
In my codebehind, I add items to the collection as in...
myCustomControl.items.Add(new myClass());
However, these are not persisted across postbacks. What is the proper way to allow persistance in custom controls?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
哎呀! 不要放置列表<> 进入视图状态! 这将是巨大的!
如果添加 List包含两个元素 - “abc”和“xyz”到 ViewState 中,它将增长 312 字节。
如果您添加一个包含相同两个元素的 string[],它只会增长 24 个字节。
这只是字符串列表! 您可以按照 Corey Downie 的建议将您的类放在那里,但是您的 ViewState 将会迅速增长!
为了保持其合理的大小,您必须付出一些努力将项目列表转换为字符串数组,然后再转换回来。
作为替代方案,请考虑将对象放入 Session 中:这样您的对象将存储在服务器上,而不是被序列化到 ViewState 中并发送到浏览器并返回。
Yikes! Don't put a List<> into the ViewState! It'll be massive!
If you add a List<string> that contains two elements - "abc" and "xyz" into the ViewState, it'll grow by 312 bytes.
If instead you add a string[] that contains the same two elements, it'll only grow by 24 bytes.
And that's just lists of strings! You can put your classes in there as Corey Downie suggests, but your ViewState will mushroom!
To keep it a sensible size, you'll have to go to some effort to convert your list of items into arrays of strings and back again.
As an alternative, consider putting your objects into the Session: that way your objects will be stored on the server, instead of being serialized into the ViewState and sent to the browser and back.
解决通用列表大小问题的一种方法是将其作为基本数组类型保存在 ViewState 中:
One way to overcome the size problem with a generic list is to persist it in ViewState as its basic array type:
如果您正在讨论在同一页面的回发之间保留数据,那么您可以手动将项目添加到 ViewState 并在加载时检索它们。
if you are talking about persisting the data across postbacks of the same page then you can manually add the items to the ViewState and the retrieve them On Load.
您可以将它们存储在控件视图状态中
You can store them in the controls viewstate
我同意 List<> 存在问题。 在视图状态但它确实有效。 请注意,设计上没有设置器。 您需要对列表对象的引用,并且您的 get 方法可以在需要时新建一个列表。
I agree that there are issues with a List<> in viewstate but it does work. Note that there is no setter on this by design. You need a reference to the list object object and your get method can new up a list when needed.