为传递的变量和值设置ViewState/Session的通用方法

本文关键字:Session ViewState 方法 变量 设置 | 更新日期: 2023-09-27 18:07:59

我现在拥有的是用于设置所需变量的ViewState或Session的代码:

 if (ViewState["currentPage"] != null)
        {
            currentPage = Convert.ToInt32(ViewState["currentPage"].ToString());
        }
        else
        {
            currentPage = 0;
            ViewState["currentPage"] = currentPage.ToString();
        }

currentPage字段是全局的,在CodeBehind中默认值为零(public int currentPage = 0;),因此无论何时加载页面,它的初始值都为零。所以我写了这几行来保存它的最后一个值。只要提到在CodeBehind中更改currentPage值的地方,我就添加"ViewState["currentPage"] = currentPage. tostring ();"

我想要的是一个通用函数,它有两个参数,变量和值,用于根据上面的代码设置ViewState。如果有必要,我可以调用setViewState(currentPage, 0)

为传递的变量和值设置ViewState/Session的通用方法

是否需要将变量作为输入参数-在应用程序的某个地方简单地在类中创建函数并传递值然后返回创建的值有什么问题?例如

public int setViewState(int value) {
  //return and set value here?
}

so的用法如下:currentValue= setViewState(50);

我认为使用全局函数的困难在于ViewState对于页面来说是本地的。

有几件事可能会对你有所帮助:

  1. 别忘了ViewState是一个对象所以你不需要使用ToString
  2. 你可以把必要的代码放在像这样的属性中:

    public int? TestInt {
        get { return ViewState["TestInt"] as int?; }
        set { ViewState["TestInt"] = value; }
    }
    

我喜欢这种方法,因为它非常明显的代码在做什么,特别是当我试图尽可能减少ViewState的使用