c# - 事件处理程序中的属性值不正确

标签 c# asp.net variables properties viewstate

我尝试在方法中设置一个值,如下所示,但是当我运行 btnSaveValue 时,没有要检索的值。我什至尝试在默认类中创建一个私有(private) int val 并将值分配给它,但仍然出现一个空白值 - 谁能帮助我?

谢谢

 public partial class _Default : System.Web.UI.Page 
{
    valueAllocation valAlloc = new valueAllocation();

    public void declaringValue()
    {
        valAlloc.setValue(5);
        int testAlloc = valAlloc.getValue();
        lblResult.Text="Value set here is:"+testAlloc;  //THIS WORKS!!!
    }
    protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
    {
        lblResult.Text = "Value now is:" + valAlloc.getValue();   //DOESNT WORK??????!!!!!
    }
}

public class valueAllocation
{
    private int val;

    public void setValue(int value)
    {
        val = value;
    }
    public string getValue()
    {
        return val;
    }

}

最佳答案

这是因为您需要使用 ViewState 等来保存每个帖子中的值。

这是与 ASP.Net 页面生命周期相关的基本问题。

基本上,每次您请求页面时,都会在每个帖子上创建一个新的页面实例,并在响应返回客户端时销毁

如果你想在回发过程中保持状态,你需要手动保存ViewState中的每个值

将整个类型存储在 ViewState 中

我认为这是你最好的选择

自定义类型

[Serializable]
public class valueAllocation
{
    public int MyValue { get; set; }
}

隐藏代码

protected valueAllocation MyObject
{
   get
   {
      if(this.ViewState["c"] != null) 
           return (valueAllocation)this.ViewState["c"];

      return null;
  }
  set
  {
      this.ViewState["c"] = value;
  }

public valueAllocation declaringValue()
{
    if (this.MyObject == null)
        this.MyObject = new valueAllocation { MyValue = 5 };

    lblResult.Text="Value set here is:"+ this.MyObject.MyValue.ToString();
    return this.MyObject;
}

protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
    declaringValue()
    lblResult.Text = "Value now is:" + declaringValue().MyValue.ToString();
}

关于c# - 事件处理程序中的属性值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558337/

相关文章:

jquery - 如何在不点击播放按钮的情况下自动播放 YouTube 视频

c# - CA2227 和 ASP.NET 模型绑定(bind)

variables - SAS:如何在 IML 语句之间传输变量?

python - 将变量分配给字符串 - 在维护值的同时打印字符串

c# - LINQ to Entities 不识别方法?

C# 阻止条目所以你不会得到 "Index was outside the bounds of the array"

javascript - 如何将服务器端类型传递给 asp.net webform 以供 javascript 使用

c# - 如何解决 MVC View 模型的堆检查漏洞?

c# - 如何在 DataColumn.Expression 中使用 IF/ELSE 或 CASE?

java - 在Java中调试时,有没有办法检测ANY变量是否设置为给定值?