1

我正在尝试创建一个简单的寻呼机用户控件,它将在 ASP.NET 中继器的页脚中使用。

每次用户单击 Next 我想将 PageCounter 增加 10 并将值保存在 ViewState 中。它在我第一次单击 lbNext 时起作用,但之后它不断重置为 10 并且ViewState["PageCounter"]为空

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

澳交所:

<%@ 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>
4

1 回答 1

1

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

于 2013-01-05T20:31:53.440 回答