保持回发之间泛型列表 [英] Maintain generic list between postbacks

查看:131
本文介绍了保持回发之间泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是什么东西在我的code-背后:

Here is what is in my code-behind:

List<Event> events = new List<Event>();

protected void Page_Load(object sender, EventArgs e)
{

}

protected void AddEvent_Click(object sender, EventArgs e)
{
    Event ev = new Event();

    ev.Name = txtName.Text;

    events.Add(ev);
}

我想一个项目每次单击Add按钮时添加到列表中,但列表是每一个回发后复位。我怎么可能保持回发之间的列表中的数据?

I want to add an item to the list every time the Add button is clicked, but the list is reset after every postback. How can I keep the data in the list between postbacks?

推荐答案

我经常使用的技术,如这一点,但请记住这可能会导致您的视图状态(如呈现到浏览器)增长相当大的:

I often use a technique such as this, although keep in mind this can cause your viewstate (as rendered to the browser) to grow rather large:

public List<Event> Events 
{
  get { return (List<Event>)ViewState["EventsList"]; }
  set { ViewState["EventsList"] = value; }
}

然后,当你要使用的名单,你会做这样的事情:

Then when you want to use the list you would do something like this:

public void AddToList()
{
    List<Event> events = Events; // Get it out of the viewstate
    ... Add/Remove items here ...
    Events = events; // Add the updated list back into the viewstate
}

另外请注意,你的事件类需要被序列化,但是这通常是简单的添加[Serializable]属性的类(除非它是一个非常复杂的类)。

Also note that your Event class will need to be serializable, but that's usually as simple as adding the [Serializable] attribute to the class (unless its a really complex class).

这篇关于保持回发之间泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆