问题
Now there are 2 buttons, let's call them "Button1" and "Button2" respectively. If I click "Button1", store "1" in ViewState["Record"]; also, if I click "Button2", store "2" in ViewState["Record"], etc.
When I click Button1⟶Button1⟶Button2⟶Button2, my expected result is: in ViewState["Record"], there are a list of records, like
[1,1,2,2].
Here is my click event code:
protected void Button1_Click(object sender, EventArgs e)
{
ViewState.Add("Record", "1");
}
protected void Button2_Click(object sender, EventArgs e)
{
ViewState.Add("Record", "2");
}
//show the viewstate result
protected void ShowResult(object sender, EventArgs e)
{
for (int i = 1; i <= 4; i++)
{
Label.Text += ViewState["Record"];
}
}
It shows "2222" instead of "1122". How can I code to resolve it?
回答1:
When you add Record key a value actually it not adds, just puts a value Record key. You always see last added value on your loop.
You should add a List to ViewState and add value to list.
Add this property
protected List<long> ViewStateList
{
get{ if(ViewState["Record"] == null) ViewState["Record"] = new List<long>();
return (List<long>)ViewState["Record"] }
}
And use like
protected void Button1_Click(object sender, EventArgs e)
{
ViewStateList.Add(1);
}
Loop
protected void ShowResult(object sender, EventArgs e)
{
foreach(long item in ViewStateList)
{
Label.Text += item.ToString();
}
}
来源:https://stackoverflow.com/questions/10257607/how-to-store-record-using-viewstate