使用ViewState时出现异常

问题描述

| 我得到这个:   System.Runtime.Serialization.SerializationException      程序集\'System.Web,版本= 4.0.0.0,区域性=中性,PublicKeyToken = b03f5f7f11d50a3a \'中的类型\'System.Web.UI.WebControls.Button \'未标记为可序列化。   说明:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。      异常详细信息:System.Runtime.Serialization.SerializationException:在程序集\'System.Web,版本= 4.0.0.0,区域性=中性,PublicKeyToken = b03f5f7f11d50a3a \'中键入\'System.Web.UI.WebControls.Button \'标记为可序列化。 当我尝试将列表保存到viewState并在Page_PreInit事件中将其恢复时,我得到了它 我设置按钮并将它们添加到列表中,然后将其保存到viewState中:
      ViewState[\"Buttons\"] = buttons;
然后,我想检索它们并将它们附加到其事件处理程序中:
  void Page_PreInit(object sender,EventArgs e)
    {

        List<Button> btn = (List<Button>)ViewState[\"Buttons\"];
        if (btn!=null)
        {
            foreach (var item in btn)
            {
                item.Width = 20;
                item.Command += obtainTopicsPerPage_Click;
                item.CommandName = tPage.ToString();
                item.Text = tPage.ToString();
            }
        }
    }
    

解决方法

        根据异常消息,
System.Web.UI.WebControls.Button
不可序列化。 (这不足为奇。)为了将某些内容保存到ViewState,它必须是可序列化的,以便可以将其完整的“ self”写入字符串并存储在ViewState页面的
hidden
表单值中。 您为什么仍要在ViewState中存储4个? ViewState对于存储较小的值很有用,否则将导致隐藏格式字段中的内容。但是整个UI控件?您想要达到什么目的? 如果您只需要基于ViewState的某些数据动态创建ѭ4then控件,那么您应该只存储最小量的数据以使之成为可能,并根据该数据在代码中创建
Button
。像这样:
List<string> btn = (List<string>)ViewState[\"ButtonStrings\"];
foreach (var str in btn)
{
    var item = new Button();
    item.Width = 20;
    item.Command += obtainTopicsPerPage_Click;
    item.CommandName = tPage.ToString();
    item.Text = tPage.ToString();
    // some use of the str from the ViewState
    // or if all you need is a count,just store an int in ViewState and use a for loop
}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...