1

我有两个单独的类:1 在 tbIndexUI.aspx.cs 页面中,另一个在 regular.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);
}
4

2 回答 2

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

于 2013-08-18T03:21:40.607 回答
0

不要让你的类库类有网页类的实例。您想要相反,您希望您的 .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它可以在页面回发中持续存在。

于 2013-08-18T03:20:09.603 回答