简体   繁体   English

动态加载用户控件时出现“无法加载视图状态”错误

[英]“Failed to load view state” Error When dynamically loading user control

I am having a User control [ascx] which is a radgrid. 我有一个用户控件[ascx],它是一个radgrid。 It also has a Edit column template which allow user to Insert/ change/update the values. 它还具有一个“编辑”列模板,该模板允许用户插入/更改/更新值。

I am loading this user control on click of a button [Say EDIT] in aspx page. 我在单击aspx页面中的[Say EDIT]按钮时正在加载此用户控件。

When I click on EDIT button of aspx page the user control loads perfectly, but when I click on the Add New Record of user control I get this error message. 当我单击aspx页面的EDIT按钮时,用户控件会完美加载,但是当我单击用户控件的“ Add New Record ,会收到此错误消息。

Failed to load viewstate. 无法加载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. 例如,当动态添加控件时,在回发期间添加的控件必须与在初始请求期间添加的控件的类型和位置匹配。

//code of user control -ascx //用户控制代码-ascx

<telerik:RadGrid AllowAutomaticDeletes="True"
    AllowAutomaticInserts="False" AllowAutomaticUpdates="False"
    Height="410px" ID="rgrd1" runat="server" AutoGenerateColumns="False"
    OnUpdateCommand="rgrd1_UpdateCommand"
    OnInsertCommand="rgrd1_InsertCommand"  OnNeedDataSource="rgrd1_NeedDataSource" GridLines="None">

    <MasterTableView CommandItemDisplay="top" CommandItemStyle-Wrap="False" CommandItemStyle-HorizontalAlign="Left"
        DataKeyNames="Type">
        <Columns>
            <telerik:GridEditCommandColumn UniqueName="EditColumn" HeaderStyle-HorizontalAlign="left"
                HeaderText="Edit" ButtonType="ImageButton">
            </telerik:GridEditCommandColumn>
            <telerik:GridTemplateColumn DataField="Type" HeaderStyle-HorizontalAlign="left"
                HeaderText="Type" UniqueName="Type">
                <ItemTemplate>
                    <asp:Label ID="TypeLabel" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
                </ItemTemplate>
            </telerik:GridTemplateColumn>

        </Columns>
        <EditFormSettings EditFormType="Template">
            <EditColumn FilterControlAltText="Filter EditCommandColumn1 column" UniqueName="EditCommandColumn1">
            </EditColumn>
            <FormTemplate>
                <table>
                        <td>
                            <telerik:RadTextBox ID="txtType" Width="50" runat="server"  Text='<%# Eval("Type") %>'>
                            </telerik:RadTextBox>

                        </td>
                    </tr>
                </table>
            </FormTemplate>
        </EditFormSettings>

    </MasterTableView>
    <HeaderStyle HorizontalAlign="Center" />
</telerik:RadGrid>

..................................... Code of my aspx page - in which i am loading the above usercontrol in Radwindow .....................................我的aspx页面的代码-我正在其中加载上述代码Radwindow中的用户控件

On click of EDIT button - below code i have written- 在点击“编辑”按钮时-我编写了以下代码-

RadWindow window = new RadWindow();
window.Height = Unit.Pixel(500);
window.Width = Unit.Pixel(500);
window.VisibleOnPageLoad = true;
UserControl uc = (UserControl)Page.LoadControl("../../Controls/TypeUserControl.ascx");
uc.EnableViewState = false;
window.ContentContainer.Controls.Add(uc);
pnl.Controls.Add(window);

When I click on Add New Record in usercontrol it throws the exception "Failed to load view state:" 当我在用户控件中单击“ Add New Record ,它将引发异常“无法加载视图状态:”

I have aspx page on which this user control is loaded is being inherited by my BasePage. 我有加载该用户控件的aspx页面被BasePage继承。

Exception is coming in OnPreRender of base page 基本页面的OnPreRender中出现异常

protected override void OnPreRender(EventArgs e)
{
    try
    {
         base.OnPreRender(e);
    }
}

User control - code behing 用户控制-代码行为

    public partial class TypeUserControl : System.Web.UI.UserControl
{

    protected void rgrd1Types_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    {
        try
        {
           //dbase call
        }
        catch (Exception ex)
        {
            SetValidationMessage(ex.Message.ToString());
        }
    }

    protected void rgrd1_InsertCommand(object source, GridCommandEventArgs e)
    {
        try
        {
            //dbase call

        }
        catch (Exception ex)
        {
            SetValidationMessage(ex.Message.ToString());
        }
    }

I don't know if this is the issue, but your HTML is not correct in your Form Template 我不知道这是否是问题,但是您的HTML在表单模板中不正确

  <table> <td> <telerik:RadTextBox ID="txtType" Width="50" runat="server" Text='<%# Eval("Type") %>'> </telerik:RadTextBox> </td> </tr> </table> 

you are missing the opening <tr> tag. 您缺少开始<tr>标记。 this could have something to do with the issue. 这可能与问题有关。

you should double check all your code to make sure that it is correct. 您应该仔细检查所有代码以确保其正确无误。

-- -

I am also guessing that you should remove this line of code from the Edit button's OnClick() event 我还猜测您应该从“编辑”按钮的OnClick()事件中删除此行代码

    uc.EnableViewState = false;

You have to recreate the control on postback as you add it dynamically. 动态添加控件时,必须在回发时重新创建控件。 Recreate or Add the control in the Init_page Eventhandler, there you can check the type of event or control, that caused the postback, to know that you should recreate this control. 在Init_page Eventhandler中重新创建或添加控件,您可以在其中检查导致回发的事件或控件的类型,以了解您应该重新创建此控件。 Can you post the code-behind file. 您可以发布代码隐藏文件吗?

EDIT: It's a long time ago, when I did this. 编辑:很久以前,当我这样做时。 But here is a working example. 但是,这是一个可行的示例。 I think there is a better way. 我认为有更好的方法。 Check the keys collection, which button caused the postback, if it is a certain button in your ascx control then readd your control to the page or whereever you put it, but it must be the same place on postback, otherwise you will get an error, I think. 检查keys集合,哪个按钮引起了回发,如果它是ascx控件中的某个按钮,则将控件读到页面上或放置在页面上的任何地方,但必须在回发上位于同一位置,否则会出现错误, 我认为。

protected override void OnInit(EventArgs e) { base.OnInit(e); 受保护的重写void OnInit(EventArgs e){base.OnInit(e);

  if (this.Page.IsPostBack) { var x = base.DeterminePostBackMode(); if (x.Keys.Get(3).Contains("btnInControl")) { Control ctrl = Page.LoadControl("WebUserControl1.ascx"); this.Page.Form.Controls.Add(ctrl); } } } 

It has been a year since you posted this issue but just in case someone still facing this: here is the main root of this type of error. 自您发布此问题以来已经一年了,但以防万一有人仍然面临此问题:这是此类错误的主要根源。 I have been struggling big time with it. 我一直在努力争取。

  • The easiest way to fix your bug is to set to the control you add dynamically : 修正错误的最简单方法是将其设置为动态添加的控件:

     EnableViewState = false 
  • If you need the Viewstate, the other options you have are to add the control you add dynamically onInit, or recreate it on every Postback. 如果需要Viewstate,则其他选项是添加在onInit中动态添加的控件,或在每次回发时重新创建它。

Hope it helps. 希望能帮助到你。

See Funkylife's comment for more information. 有关更多信息,请参见Funkylife的评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM