计数器在回发时损失价值 [英] Counter loses value on postback

查看:40
本文介绍了计数器在回发时损失价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的照片创建一个简单的画廊.我是asp.net的新手.
每当我单击下一个照片按钮时,计数器在回发时都会丢失值,并保留在同一张图像上.
我如何制作一个不会失去价值的柜台?还是我有其他方法可以做到这一点?
请用简单的英语解释,记住我是新手.谢谢.


Hi, I''m creating a simple gallery for my photos. I''m quite new to asp.net.
Whenever I click on the next photo button, the counter loses value on the postback and remains on the same image.
How can I make a counter that doesn''t lose value? Or is there any other way I can do this at all?
Please explain in simple English, remember I''m new to this. thanks.


int counter = 0;
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
       {
           counter++;
           ImageGallery.ImageUrl = "~/Images/" + counter.ToString() + ".jpg";

推荐答案

Web应用程序无法维持Windows应用程序之类的状态.定义的任何类成员都将在页面请求(或有时称为往返或回发等)处理期间重建.但是有很多其他方法可以维护变量的状态.但是我在这里列出了几种保存变量以供下一个请求的方法.
1)存储在会话中.例如:
在ImageButton2_click内,
if(Session ["counter"]!= null)
{
counter = Convert.ToInt32(Session ["counter"]);
}

Session ["counter"] = ++ counter
2)HiddenField元素,像在Session示例中一样进行读取/存储.

要了解有关ASP.NET/Web应用程序的更多信息,除阅读书籍外,我建议练习Visual Studio安装的示例.
Web application cannot maintain state like Windows application. Any class member defined will be reconstructed during the page request(or sometimes called roundtrip or postback etc) processing. But there are bunch of alternative ways that you can maintain state of a varible.But I list here couple of ways to save the variable for the next request.
1)Store in Session. ex:
inside the ImageButton2_click,
if(Session["counter"]!=null)
{
counter = Convert.ToInt32(Session["counter"]);
}

Session["counter"] = ++counter
2)HiddenField element, read/store like it is done in Session example.

To learn more about ASP.NET/Web Applications, I suggest practice Visual Studio installed samples besides reading the books.


这篇关于计数器在回发时损失价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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