下面是什么东西在我的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).