如何使用Repeater上的按钮更改视图?

Bru*_*oLM 5 c# asp.net

我有以下结构

<asp:UpdatePanel ID="MyUpdatePanel" runat="server">
    <ContentTemplate>
        <asp:MultiView ID="MyViews" runat="server">
            <asp:View ID="List" runat="server">
                <asp:Repeater runat="server" ID="Repeater1">
                    <ItemTemplate>
                        <asp:LinkButton ID="Button1" runat="server" Text="Button1" CommandName="View" />
                    </ItemTemplate>
                </asp:Repeater>
            </asp:View>
            <asp:View ID="Single" runat="server">
                <asp:LinkButton ID="Button2" runat="server" Text="Button2" />
            </asp:View>
        </asp:MultiView>
    </ContentTemplate>
</asp:UpdatePanel>
Run Code Online (Sandbox Code Playgroud)

在后面的代码我得到转发器ItemDataBound事件,得到控件使用var button1 = e.Item.FindControl("Button1") as LinkButton;然后我分配一个CommandArgument与当前元素的ID.

这是在CreateChildControls方法之后立即执行的.

Repeater1.ItemDataBound += (s, e) =>
{
    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
    {
        var Button1 = e.Item.FindControl("Button1") as LinkButton;
        Button1.CommandArgument = item.ID.ToString();
    }
};

Repeater1.ItemCommand += (s, e) =>
{
    if (e.CommandName == "View")
    {
        var item = provider.Get(Convert.ToInt64(e.CommandArgument));
        BuildSingleView(item);
    }
};
Run Code Online (Sandbox Code Playgroud)

这个方法只是改变视图......

public void BuildSingleView(var item)
{
    MyViews.ActiveViewIndex = 1;
    /* Edit
       I've tried to call here
       Initialize(), EnsureChildControls(), CreateChildControls()
       but it was a useless try. I also tried to catch exceptions,
       but none happened.
     */
}
Run Code Online (Sandbox Code Playgroud)

问题是视图不会改变.当我单击LinkBut​​ton时它会执行CreateChildControls并在它调用事件之后ItemCommand,事件调用BuildSingleView,ActiveViewIndex更改但页面上没有任何反应.

我不明白为什么它不会改变.这是事件顺序的问题吗?单击LinkBut​​ton时,如何更改视图?


这是完整的代码隐藏代码(Initialize方法是在CreateChildControls之后立即执行的方法)http://pastebin.com/2qwrKNxf

这里有完整的ascx文件http://pastebin.com/P8RSbY9U

Bru*_*oLM 0

我发现当更新面板发回时,它不会首先调用事件处理程序。因此,为了让它执行,我需要重新分配事件。

我的问题是控件没有保存 ViewState,因此它不断创建错误的事件。我用会话替换了 ViewState,并得到了我想要的行为。