UserControl在回发后丢失ViewState

时间:2013-01-05 19:59:31

标签: c# asp.net user-controls viewstate

我正在尝试创建一个简单的寻呼机用户控件,该控件将用于ASP.NET转发器的页脚。

每次用户单击“下一步”时,我希望将PageCounter增加10并将值保存在ViewState中。 它在我第一次单击lbNext时工作,但之后它一直重置为10并且ViewState["PageCounter"]为空

我尝试用[PersistenceMode(PersistenceMode.Attribute)]装饰我的财产,但仍然没有运气。为什么值没有被持久化到ViewState?

ASCX:

<%@ Control Language="C#" EnableViewState="true" AutoEventWireup="true" CodeBehind="Pager.ascx.cs" Inherits="WebApplication6.Pager" %>
<asp:LinkButton ID="lbPrevious" runat="server" OnCommand="SetPage" CommandArgument="Previous">Previous</asp:LinkButton>
<asp:TextBox ID="txtPage" runat="server" EnableViewState="true" Enabled="false"></asp:TextBox>
<asp:LinkButton ID="lbNext" runat="server" OnCommand="SetPage" CommandArgument="Next">Next</asp:LinkButton>

代码背后:

public partial class Pager : System.Web.UI.UserControl
{
    [PersistenceMode(PersistenceMode.Attribute)]
    public int PageCounter
    {
        get
        {
            var counter = ViewState["PageCounter"];
            return ((counter == null) ? 0 : (int)counter);
        }
        set
        {
            ViewState["PageCounter"] = value;
            txtPage.Text = value.ToString();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            PageCounter = 0;
    }

    protected void SetPage(object sender, CommandEventArgs e)
    {
        switch (e.CommandArgument.ToString())
        {
            case "Previous":
                PageCounter -= 10;
                break;
            case "Next":
                PageCounter = PageCounter + 10;
                break;
        }
    }
}

修改

以下是我将Pager用户控件添加到转发器的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Repeater.aspx.cs" Inherits="WebApplication6.Repeater" %>
<%@ Register Src="Pager.ascx" TagName="Pager" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Repeater control</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Repeater ID="booksRepeater" runat="server">
        <ItemTemplate>
            <table>
                <tr>
                    <td>
                        Name:&nbsp;<asp:Label ID="lblName" runat="server" Text='<%# Bind("FirstName") %>' />
                    </td>
                </tr>
                <tr>
                    <td>
                        Surname:&nbsp;<asp:Label ID="lblSurname" runat="server" Text='<%# Bind("LastName") %>' />
                    </td>
                </tr>
            </table>
            </div>
        </ItemTemplate>
        <FooterTemplate>
            <asp:Pager ID="pager" runat="server" />
        </FooterTemplate>
    </asp:Repeater>
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

当您的数据绑定到Repeater(“booksRepeater”)时,您的代码不会显示。确保及时绑定数据。 听起来像这个问题:Maintaining viewstate of a repeater