[英]How to store record using ViewState
Now there are 2 buttons, let's call them "Button1" and "Button2" respectively. 现在有2个按钮,我们分别称它们为“Button1”和“Button2”。 If I click "Button1", store "1" in ViewState["Record"];
如果单击“Button1”,则在ViewState [“Record”]中存储“1”; also, if I click "Button2", store "2" in ViewState["Record"], etc.
另外,如果我点击“Button2”,在ViewState [“Record”]等中存储“2”等。
When I click Button1⟶Button1⟶Button2⟶Button2, my expected result is: in ViewState["Record"], there are a list of records, like 当我点击Button1⟶Button1⟶Button2⟶Button2时,我的预期结果是:在ViewState [“Record”]中,有一个记录列表,如
[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". 它显示“2222”而不是“1122”。 How can I code to resolve it?
我该如何编码来解决它?
When you add Record key a value actually it not adds, just puts a value Record key. 当你添加一个实际上没有添加的值时,只需添加一个值Record键。 You always see last added value on your loop.
您始终可以在循环中看到最后一个附加值。
You should add a List to ViewState and add value to list. 您应该向ViewState添加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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.