2013-08-18 83 views
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); 
} 

回答

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

+0

毛之间持久化数据的不同方式下面的指南,我尝试使用您在显示的ViewState你的例子,但价值观不成立。当我遍历代码时,值正在被声明,但是当它进入aspx.cs页面时,Viewstates被重置为null。任何想法发生了什么? – snapplex

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代码

现在,你有​​一个实例,随时随地你存储例如在Session缓存或ViewState所以它可以跨页回发坚持。