用户控件的属性在回发后失去价值

User control#39;s property loses value after a postback(用户控件的属性在回发后失去价值)

本文介绍了用户控件的属性在回发后失去价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 HTML.我有一个包含用户控件的中继器.

This is the HTML. I have a repeater that contains a user control.

<asp:Repeater ID="rpNewHire" runat="server">
 <HeaderTemplate>
  <table>            
 </HeaderTemplate>
 <ItemTemplate>
  <tr>
     <td>
         <user:CKListByDeprtment ID = "ucCheckList" 
          DepartmentID= '<%# Eval("DepID")%>' 
          BlockTitle = '<%# Eval("DepName")%>' 
          runat = "server"></user:CKListByDeprtment>
     </td>
   </tr>
  </ItemTemplate>
  <FooterTemplate>
   </table>
  </FooterTemplate>
</asp:Repeater>

DepartmentID 是我在用户控件中定义的一个属性.

DepartmentID is a property that I defined inside the user control.

int departmentID;

public int DepartmentID
{
  get { return departmentID; }
  set { departmentID = value; }
}

这就是我尝试访问它的方式

And this is how I am trying to access it

protected void Page_Load(object sender, EventArgs e)
{
   int test = departmentID;
}

第一次加载页面时,departmentID 有一个值.但是,当页面回发时,该值始终为 0.

When the page loads for the first time, departmentID has a value. However, when the page Posts back, that value is always 0.

推荐答案

所有变量(和控件)都在页面生命周期结束时被释放.所以你需要一种方法来持久化你的变量,例如在 ViewState 中.

All variables (and controls) are disposed at the end of the page's lifecycle. So you need a way to persist your variable, e.g. in the ViewState.

public int DepartmentID
{
    get {
        if (ViewState["departmentID"] == null)
            return int.MinValue;
        else 
            return (int)ViewState["departmentID"]; 
    }
    set { ViewState["departmentID"] = value; }
}

MSDN 杂志文章在 ASP.NET 应用程序中管理持久用户状态的九个选项"很有用,但在 MSDN 网站上不再可见.它是 2003 年 4 月版,您可以下载为 Windows 帮助文件 (.chm).(不要忘记调出属性并取消阻止这是从互联网上下载的"的东西,否则您无法查看文章.)

The MSDN Magazine article "Nine Options for Managing Persistent User State in Your ASP.NET Application" is useful, but it's no longer viewable on the MSDN website. It's in the April 2003 edition, which you can download as a Windows Help file (.chm). (Don't forget to bring up the properties and unblock the "this was downloaded from the internet" thing, otherwise you can't view the articles.)

这篇关于用户控件的属性在回发后失去价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:用户控件的属性在回发后失去价值

基础教程推荐