Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 将控件序列化为viewstate_Asp.net_Custom Controls_Viewstate_User Controls - Fatal编程技术网

Asp.net 将控件序列化为viewstate

Asp.net 将控件序列化为viewstate,asp.net,custom-controls,viewstate,user-controls,Asp.net,Custom Controls,Viewstate,User Controls,我正在编写一个自定义用户控件。我觉得我这样做很难 我知道为了在回发之间保留控件的状态,我必须将数据保存到ViewState。我已经在我的用户控件类中的几个字段中完成了这项工作 然而,这似乎很乏味。是否有一种方法可以让ASP.net在页面加载完成后将用户控件中的所有可序列化字段一次性保存到ViewState?我有一个解决方案,您仍然需要根据您的情况进行调整,因为此示例(重新)存储控件的所有状态,以及ASP.net运行时设置的属性。请记住,Serializable不能在field的属性上设置,只能在

我正在编写一个自定义用户控件。我觉得我这样做很难

我知道为了在回发之间保留控件的状态,我必须将数据保存到ViewState。我已经在我的用户控件类中的几个字段中完成了这项工作


然而,这似乎很乏味。是否有一种方法可以让ASP.net在页面加载完成后将用户控件中的所有可序列化字段一次性保存到ViewState?

我有一个解决方案,您仍然需要根据您的情况进行调整,因为此示例(重新)存储控件的所有状态,以及ASP.net运行时设置的属性。请记住,Serializable不能在field的属性上设置,只能在类/结构上设置。但是,您可以创建自己的属性(ViewStateSerializable?),用于修饰回发期间要保留的属性。请记住,viewstate是通过连接到客户端的,因此如果您有很多it用户可能会感到不安

protected override object SaveViewState()
{
    Dictionary<string, object > dict = new Dictionary<string, object>();
    foreach (var prop in this.GetType().GetProperties())
    {
        // here we decide what to save
        if (prop.PropertyType.GetCustomAttributes(
              typeof(SerializableAttribute), false).Length>0)
        {
            dict.Add(prop.Name, prop.GetValue(this, new object[] {}));
        }
    }

    var ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, dict);

    return ms.ToArray();
}


protected override void LoadViewState(object savedState)
{
    BinaryFormatter bf = new BinaryFormatter();
    Dictionary<string, object> dict = 
        (Dictionary<string, object>) bf.Deserialize(
        new MemoryStream((byte[])savedState));

    foreach(var kv in dict)
    {
        this.GetType()
            .GetProperty(kv.Key)
            .SetValue(this, kv.Value, new object[] {});
    }
    base.LoadViewState(savedState);
}
受保护的覆盖对象SaveViewState()
{
Dictionary dict=新字典();
foreach(此.GetType().GetProperties()中的var prop)
{
//在这里,我们决定保存什么
如果(prop.PropertyType.GetCustomAttributes(
typeof(SerializableAttribute),false。长度>0)
{
dict.Add(prop.Name,prop.GetValue(this,新对象[]{}));
}
}
var ms=新内存流();
BinaryFormatter bf=新的BinaryFormatter();
bf.序列化(ms、dict);
返回ToArray女士();
}
受保护的覆盖无效LoadViewState(对象保存状态)
{
BinaryFormatter bf=新的BinaryFormatter();
字典dict=
(字典)bf.反序列化(
新的MemoryStream((字节[])savedState));
foreach(以dict为单位的var kv)
{
this.GetType()
.GetProperty(千伏键)
.SetValue(此,千伏值,新对象[]{});
}
base.LoadViewState(savedState);
}