如何序列化ViewState对象

本文关键字:对象 ViewState 序列化 | 更新日期: 2023-09-27 18:08:26

我有一些函数可以查询数据库并将结果放入网格视图中。它还设置了一个ViewState变量,该变量包含查询的结果。当我回发时,我有一个加载函数,它从最后的结果(如果有的话(加载网格视图。

我遇到的问题是,我得到了一个错误,基本上说viewstate对象需要序列化。据我所知,我不知道该怎么做。

错误:Sys.WebForms.PageRequestManagerServerErrorException:错误序列化值'System.Collections.Generic.List 1[<>f__AnonymousType17 2[System.Int32,System.String]]'类型'System.Collections.Generic.List 1[[<>f__AnonymousType17 2[[System.Int32,mscorlib,版本=4.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089],[System.String,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],App_Web_rjb524gi,版本=0.0.0.0,区域性=中性,PublicKeyToken=null]].'

到目前为止我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Runtime.Serialization;
public partial class PlayersManagement : System.Web.UI.Page
{ 
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        LoadData();
    }
}
public void LoadData()
{
    if (ViewState["CurrentGridView"] != null || ViewState["CurrentGridView"] == "")
    {
        GridViewPlayers.DataSource = ViewState["CurrentGridView"];
        GridViewPlayers.DataBind();
    }
    else
    {
        DBModel.DBEntities context = new  DBModel.DBEntities();
        var players= (from f in context.Players
                        where f.isDeleted == false
                        select new
                        {
                            f.PlayerId,
                            f.PlayerName
                        }).ToList();
        GridViewPlayers.DataSource = players;
        GridViewPlayers.DataBind();
    }
    ViewState["Sort"] = 0;
}

/**
   * This method is for advance search functionality 
   * 
   */
protected void btnSearch_Click(object sender, EventArgs e)
{
    // If the search textbox is not empty
    if (txtSearch.Text.Trim() != "")
    {
        // Call to Entity Model Framework
       DBModel.DBEntities context = new DBModel.DBEntities();
        //Querying the Players table 
        var search = (from s in context.Players
                      where s.PlayerName.Contains(txtSearch.Text.Trim())
                      select new
                      {
                          s.PlayerId,
                          s.PlayerName
                      }).ToList();

        if (search.Count != 0)
        {
            noResults.Visible = false;
            GridViewPlayers.DataSource = search;//Connecting query to the datasource Gridview
            ViewState["CurrentGridView"] = search; // <---- Error cause here
            GridViewPlayers.DataBind();  //Binding Gridview
        }
        else
        {
            noResults.Visible = true;
            noResults.Text = "This '" + txtSearch.Text + "' Query Returned No Results";
            txtSearch.Text = "";
        }

    }
}

 protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
    //Label2.Text = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
     DBModel.DBEntities context = new  DBModel.DBEntities();
    var players = (from b in context.Players
                 where b.isDeleted == false
                 select b);
    DataTable gridviewTable = players.CopyToDataTable();
    gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    GridViewPlayers.DataSource = gridviewTable;
    ViewState["CurrentGridView"] = gridviewTable; <--- Also causes error
    GridViewPlayers.DataBind();
}

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
    string newSortDirection = String.Empty;
    int sort = (ViewState["Sort"] == null) ? 0 : (int)ViewState["Sort"];
    switch (sort)
    {
        case 0:
            newSortDirection = "ASC";
            ViewState["Sort"] = 1;
            break;
        case 1:
            newSortDirection = "DESC";
            ViewState["Sort"] = 0;
            break;
    }
    return newSortDirection;
}
protected void GridViewPlayers_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridViewPlayers.EditIndex = e.NewEditIndex;
    LoadData();
}

protected void GridViewPlayers_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
    GridViewPlayers.EditIndex = -1;
    LoadData();
}

如何序列化ViewState对象

如果您真的想将其存储在View State中,那么您可能想要一个可以标记为[Serializable]的类型。看起来匿名类型不是。因此,不使用:

var search

使用

 List<Player> search =  Query  

还有课堂。

[Serializable]
public class Player
{
    public int PlayerId {get;set;}
    public string PlayerName {get;set;}
}

然而,看起来你每次都在查询数据库,所以即使你在视图状态下存储,你也不会得到任何东西。

问题是,不能使用ViewState传递匿名对象。一种解决方案是创建强类型模型,并使用它们作为匿名对象。创建Player类:

public class Player
{
    public Int32 PlayerId { get; set; }
    public String PlayerName { get; set; }
}

并像这样使用:

var search = (from s in context.Players
    where s.PlayerName.Contains(txtSearch.Text.Trim())
    select new Player
    {
        PlayerId = s.PlayerId,
        PlayerName = s.PlayerName
    }).ToList();

而不是:

var search = (from s in context.Players
    where s.PlayerName.Contains(txtSearch.Text.Trim())
    select new
    {
        s.PlayerId,
        s.PlayerName
    }).ToList();

对所有动态结果(将它们更改为使用具体类(和绑定分别执行此操作。序列化响应。通过CCD_ 6应该正常工作。