ASP.NET 2.0 Viewstate Issue

Posts   
 
    
bdeline
User
Posts: 13
Joined: 13-Jul-2006
# Posted on: 21-Aug-2006 00:04:34   

Hi, Sorry to have to post this issue to this forum because it isn't necessary llblgen related but after an hour of baning my head on this I'm not sure where to turn. I have a .aspx page with two panels on it, one that hold a panel for a gridview and the other a panel that holds a formview control that has itself bound to the gridview's selected index. The gridview is displayed first to the user. They select an item, the gridview panel is hidden and the formview panel is visible with the data from the gridview's selected index. The user makes any changes and clicks the update link on the formview. The formview panel is hidden and the gridview panel is visible. Everything works up to this point, but one I click on the select link from the gridview again I get the following error from asp.net:


Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. 

I know this is a problem when you are doing dynamically loaded controls on a page. However as far as I can tell I don't have any dynamically loaded controls. Can anyone shine some insight where I have gone wrong. An additional note, I have a page that works similiar to this page in terms of a gridview and formview toggling between each other and it does not exhibit above behavior. My codes is below.

.ASPX


<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ListUsers.aspx.cs" Inherits="Admin_Client_ListUsers" Title="Untitled Page" Theme="Default"%>

<%@ Register Assembly="SD.LLBLGen.Pro.ORMSupportClasses.NET20" Namespace="SD.LLBLGen.Pro.ORMSupportClasses"
    TagPrefix="cc1" %>


<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <br />
    <asp:Panel ID="pnlForm" runat="server" Visible="true">
        <asp:FormView ID="fvUserInfo" runat="server" DataKeyNames="UserInfoGuid" DataSourceID="LLBLGenProDataSource2"
            Width="456px" CellPadding="4" ForeColor="#333333"
            OnItemUpdated="fvUserInfo_OnItemUpdated"
            OnItemInserting="fvUserInfo_OnItemInserting"
            OnItemInserted="fvUserInfo_OnItemInserted">
            <EditItemTemplate>
                FirstName:
                <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox><br />
                LastName:
                <asp:TextBox ID="LastNameTextBox" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox><br />
                Username:
                <asp:TextBox ID="UsernameTextBox" runat="server" Text='<%# Bind("Username") %>'></asp:TextBox><br />
                Password:
                <asp:TextBox ID="PasswordTextBox" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox><br />
                Active:
                <asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Bind("Active") %>' /><br />
                Roles:
                <asp:CheckBoxList ID="chkList" runat="server" DataSourceID="LLBLGenProDataSource3"
                    DataTextField="Name" DataValueField="RoleGuid"
                    OnDataBound="chkList_OnDataBound">
                </asp:CheckBoxList><asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                    CommandName="Update" Text="Update"></asp:LinkButton>
                <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
                    Text="Cancel" OnClick="CancelButton_Click"></asp:LinkButton>
            </EditItemTemplate>
            <InsertItemTemplate>
                FirstName:
                <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>'>
                </asp:TextBox><br />
                LastName:
                <asp:TextBox ID="LastNameTextBox" runat="server" Text='<%# Bind("LastName") %>'>
                </asp:TextBox><br />
                Username:
                <asp:TextBox ID="UsernameTextBox" runat="server" Text='<%# Bind("Username") %>'>
                </asp:TextBox><br />
                Password:
                <asp:TextBox ID="PasswordTextBox" runat="server" Text='<%# Bind("Password") %>'>
                </asp:TextBox><br />
                Active:
                <asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Bind("Active") %>' /><br />
                <br />
                Roles:
                <asp:CheckBoxList ID="chkList" runat="server" DataSourceID="LLBLGenProDataSource3"
                    DataTextField="Name" DataValueField="RoleGuid"/>
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
                    Text="Insert">
                </asp:LinkButton>
                <asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
                    Text="Cancel">
                </asp:LinkButton>
            </InsertItemTemplate>
            <ItemTemplate>
                FirstName:
                <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label><br />
                LastName:
                <asp:Label ID="LastNameLabel" runat="server" Text='<%# Bind("LastName") %>'></asp:Label><br />
                Username:
                <asp:Label ID="UsernameLabel" runat="server" Text='<%# Bind("Username") %>'></asp:Label><br />
                Password:
                <asp:Label ID="PasswordLabel" runat="server" Text='<%# Bind("Password") %>'></asp:Label><br />
                CreateDate:
                <asp:Label ID="CreateDateLabel" runat="server" Text='<%# Bind("CreateDate") %>'></asp:Label><br />
                ModDate:
                <asp:Label ID="ModDateLabel" runat="server" Text='<%# Bind("ModDate") %>'></asp:Label><br />
                Active:
                <asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Bind("Active") %>'
                    Enabled="false" /><br />
                Roles:
                <asp:CheckBoxList ID="chkList" runat="server" DataSourceID="LLBLGenProDataSource3"
                    DataTextField="Name" DataValueField="RoleGuid" Enabled="false"
                    OnDataBound="chkList_OnDataBound"/>
                <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit"
                    Text="Edit"></asp:LinkButton>
                &nbsp;
                <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
                    Text="Cancel"></asp:LinkButton>
            </ItemTemplate>
        </asp:FormView>
        <cc1:LLBLGenProDataSource ID="LLBLGenProDataSource2" runat="server" DataContainerType="EntityCollection"
            EntityCollectionTypeName="DiamondMSI.CollectionClasses.UserInfoCollection, DiamondMSI" SortingMode="ServerSide">
            <SelectParameters>
                <asp:ControlParameter ControlID="GridView1" Name="UserInfoGuid" PropertyName="SelectedValue" />
            </SelectParameters>
        </cc1:LLBLGenProDataSource>
        <cc1:LLBLGenProDataSource ID="LLBLGenProDataSource3" runat="server" DataContainerType="EntityCollection"
            EntityCollectionTypeName="DiamondMSI.CollectionClasses.RoleCollection, DiamondMSI">
        </cc1:LLBLGenProDataSource>
        <br />
        <br /> 
    </asp:Panel>
    
    <asp:Panel ID="pnlList" runat="server" Visible="true">
    <asp:LinkButton ID="lbNewUser" runat="server" OnClick="lbNewUser_Click">Create New User</asp:LinkButton>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="UserInfoGuid"
        DataSourceID="LLBLGenProDataSource1" AllowPaging="True" AllowSorting="True" CellPadding="4" ForeColor="#333333" 
        GridLines="None"
        OnSelectedIndexChanging="gv_OnSelectedIndexChanged">
        <Columns>
            <asp:BoundField DataField="CompanyGuid" HeaderText="CompanyGuid" SortExpression="CompanyGuid" />
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
            <asp:BoundField DataField="Username" HeaderText="Username" SortExpression="Username" />
            <asp:BoundField DataField="CreateDate" HeaderText="CreateDate" SortExpression="CreateDate" />
            <asp:BoundField DataField="ModDate" HeaderText="ModDate" SortExpression="ModDate" />
            <asp:CheckBoxField DataField="Active" HeaderText="Active" SortExpression="Active" />
            <asp:CommandField ShowSelectButton="True" />
        </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <EditRowStyle BackColor="#999999" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    </asp:GridView>
    <cc1:LLBLGenProDataSource ID="LLBLGenProDataSource1" runat="server" DataContainerType="EntityCollection"
        EntityCollectionTypeName="DiamondMSI.CollectionClasses.UserInfoCollection, DiamondMSI">
        <SelectParameters>
            <asp:QueryStringParameter Name="CompanyGuid" QueryStringField="CompanyGuid" />
        </SelectParameters>
    </cc1:LLBLGenProDataSource>
    </asp:Panel>
</asp:Content>

.ASPX.CS


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using SD.LLBLGen.Pro.ORMSupportClasses;
using DiamondMSI.CollectionClasses;
using DiamondMSI.EntityClasses;
using DiamondMSI.HelperClasses;

public partial class Admin_Client_ListUsers : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        FormViewMode fmv = fvUserInfo.CurrentMode;
    }

    protected void gv_OnSelectedIndexChanged(object sender, GridViewSelectEventArgs e)
    {
        pnlForm.Visible = true;
        pnlList.Visible = false;
    }

    protected void CancelButton_Click(object sender, EventArgs e)
    { 
        pnlForm.Visible = false;
        pnlList.Visible = true;
    }


    protected void chkList_OnDataBound(object sender, EventArgs e)
    {
        UserInfoEntity uie = new UserInfoEntity(new Guid(fvUserInfo.DataKey.Value.ToString()));
        RoleCollection rc = uie.GetMultiRoleCollectionViaUserInfoRole(true);
        foreach (ListItem li in ((CheckBoxList)sender).Items)
        {
            IPredicateExpression filter = new PredicateExpression(RoleFields.RoleGuid == new Guid(li.Value));

            if (rc.FindMatches(filter).Count > 0)
            {
                li.Selected = true;
            }
        }
    }

    protected void SaveRoles(UserInfoEntity uie, CheckBoxList cblRoles)
    {
        uie.GetMultiUserInfoRole(true).DeleteMulti();

        foreach (ListItem li in cblRoles.Items)
        {
            if (li.Selected)
            {
                RoleEntity re = new RoleEntity(new Guid(li.Value));
                UserInfoRoleEntity uire = new UserInfoRoleEntity();
                uire.UserInfo = uie;
                uire.Role = re;
                uire.UserInfoRoleGuid = Guid.NewGuid();
                uire.Save();
            }
        }
    }

    protected void fvUserInfo_OnItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {
        UserInfoEntity uie = new UserInfoEntity(new Guid(fvUserInfo.DataKey.Value.ToString()));
        CheckBoxList cbl = (CheckBoxList)fvUserInfo.FindControl("chkList");

        SaveRoles(uie, cbl);

        pnlForm.Visible = false;
        pnlList.Visible = true;

    }

    protected void lbNewUser_Click(object sender, EventArgs e)
    {
        fvUserInfo.ChangeMode(FormViewMode.Insert);
    }

    protected void fvUserInfo_OnItemInserting(object sender, FormViewInsertEventArgs e)
    {
        e.Values.Add("UserInfoGuid", Guid.NewGuid());
        e.Values.Add("CompanyGuid", Request.QueryString["CompanyGuid"]);
    }

    protected void fvUserInfo_OnItemInserted(object sender, FormViewInsertedEventArgs e)
    {
        UserInfoEntity uie = new UserInfoEntity(new Guid(fvUserInfo.DataKey.Value.ToString()));
        CheckBoxList cbl = (CheckBoxList)fvUserInfo.FindControl("chkList");

        SaveRoles(uie, cbl);
    }
}

Thanks. Brett

Walaa avatar
Walaa
Support Team
Posts: 14994
Joined: 21-Aug-2005
# Posted on: 21-Aug-2006 05:25:18   

What's that line doing in the Page_Load event handler? Would you try to move it to the Page_Init event handler?

Jessynoo avatar
Jessynoo
Support Team
Posts: 296
Joined: 19-Aug-2004
# Posted on: 22-Aug-2006 17:46:13   

Hi,

I find it hard to analyse because of all the datasource plumbings. My feeling is that there is some kind of mixing binding the roles through your source3, which should be done once and binding the userroles through your source2. It might be a question of event plumbing

bdeline
User
Posts: 13
Joined: 13-Jul-2006
# Posted on: 24-Aug-2006 14:09:16   

Hi, Thanks for the responses so far. I'm still working on this. Walaa, that line you are referring to in the Page_load method was just me trying to capture some information on the current mode of the FormView. I will put it in the Page_init method and see what happens. If that doesn't give me some more information to work with I'm going to try building the page from scratch adding each element in piece by piece to see if I can track down the culprit here. Jessynoo, the FormView displays a user and diplays the all roles that a user maybe a member of. Some code is fired once the Role checkbox list is bound to look up the roles a user is a member of and check the appropriate checkbox. Thanks. Brett

Jessynoo avatar
Jessynoo
Support Team
Posts: 296
Joined: 19-Aug-2004
# Posted on: 24-Aug-2006 19:39:08   

Jessynoo, the FormView displays a user and diplays the all roles that a user maybe a member of. Some code is fired once the Role checkbox list is bound to look up the roles a user is a member of and check the appropriate checkbox.

I think that's what I had understood in your code. But indeed my statement was wrong since you do rebind the global role list on every user select. Still, I think that the checkbox list may be the pb since it does contain dynamically generated controls.

What happens when you perform a postback with no event triggered ? (add an empty button to check). I guess you still get the error, which would mean it's not really about the second selection but rather the fact that your bound controls, your checkboxes I think, disappear after the second postback. Then check if having a hard coded checkbox list makes the difference to surely identify the problem source.

Maybe you can check the checkbox's list EnableViewstate or similar properties. The default should be ok though.

I had the problem once with nested datalists, and we fixed it with page_init binding to restore the structure before the viewstate gets recalled.

you may also have a look at Bauer's dynamic controls placeholder, which gives some insights. www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

Hope you'll find a solution, and I'll be happy to hear about it.