【问题标题】:passing values between separate classes在不同的类之间传递值
【发布时间】:2013-08-18 03:04:43
【问题描述】:

我有两个单独的类:1 在 tbIndexUI.aspx.cs 页面中,另一个在常规.cs 类文件中。 我想将两个数据成员从常规的 .cs 类文件传递到 .aspx 页面,但是每次“Page_Load”方法触发它都会重置之前传递的所有值。我尝试将“Page_Load”中的所有内容都注释掉,结果我将方法全部删除,但参数值仍在重置。

有没有办法将这些值传递给并维护它们?当我迷路时,任何例子都会非常有帮助。我查看了这个[example],但没有成功。

我的 aspx.cs 页面的代码

public partial class tbIndexUI : System.Web.UI.UserControl
{
    private int _numOfCols = 0;
    private int itemsPerCol = 0;

    public int numColumns
    {
        set
        {
            _numOfCols = value;
        }
    }

    public int itemsPerColumn
    {
        set
        {
            _itemsPerCol = value;
        }
    }
    public static void passData(int numOfCol, int itemsPerCol)
    {
        numColumns = numOfCol;
        itemsPerColumn = itemsPerCol;
    }
 }

我的常规课程 process.cs 的代码

void sendInformation()
{
    tbIndexUI.passData(numOfCols, itemsPerCol);
}

【问题讨论】:

    标签: c# class static-members


    【解决方案1】:
    public partial class tbIndexUI : System.Web.UI.UserControl
    {
        public int numColumns
        {
            set
            {
                ViewState["numOfCols"] = value;
            }
        }
    
        public int itemsPerColumn
        {
            set
            {
                ViewState["itemsPerCol"] = value;
            }
        }
        public static void passData(int numOfCol, int itemsPerCol)
        {
            numColumns = numOfCol;
            itemsPerColumn = itemsPerCol;
        }
    
        //when you need to use the stored values
        int _numOfCols = ViewState["numOfCols"] ;
        int itemsPerCol = ViewState["itemsPerCol"] ;
     }
    

    我建议您阅读以下指南,了解在页面和页面加载之间保存数据的不同方式

    http://www.codeproject.com/Articles/31344/Beginner-s-Guide-To-View-State

    【讨论】:

    • Mauricio,我尝试使用您在示例中显示的 ViewState,但值不成立。当我单步执行代码时,值被正确声明,但是当它进入 aspx.cs 页面时,Viewstates 被重置为 null。知道发生了什么吗?
    【解决方案2】:

    不要让你的类库类有网页类的实例。您希望相反,您希望 .aspx 页面/控件在“常规” .cs 文件中具有类的实例,因为这使它们可以跨多个页面重用。

    按照您发布的代码的编写方式,sendInformation 方法不能用于任何其他网页,因为它是硬编码的,可以使用 tbIndexUI 控件。

    相反,您希望拥有一个包含sendInformation 方法的类名(您没有在发布的代码中指出)的实例。这样做允许类保存numOfColsitemsPerCol 值并通过属性将它们公开给网页/控件。

    你可以这样写:

    public class TheClassThatHoldsNumOfColsAndItemsPerCol
    {
        public int NumOfCols { get; set; }
        public int ItemsPerCol { get; set; }
    
        // Method(s) here that set the values above
    }
    

    现在在您的 aspx 代码中,您有一个 TheClassThatHoldsNumOfColsAndItemsPerCol 的实例,并且您可以随时将该实例存储在 Session 缓存或 ViewState 中,以便它可以在页面回发中持续存在。

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 2012-04-14
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2016-05-03
      • 1970-01-01
      相关资源
      最近更新 更多