简体   繁体   中英

DIctionary retrieved from ViewState does not contain a key

I have a code that inserts <key,value> into Dictionary , put Dictionary into ViewState and than later on retrieves that Dictionary from ViewState .

This is when I populate Dictionary and put it in ViewState :

foreach (DataTable table in IsoDataSet.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        if (dr.IsNull("email"))
        {
            email = "No emails on file";
        }
        else
        {
            email = (String)dr["email"];
        }

        oldEmails.Add((String)dr["isonum"], email);
        ViewState["OldEmails"] = oldEmails;
    }
}

Then I need to get Dictionary back from ViewState :

oldEmails = (Dictionary<String, String>)ViewState["OldEmails"];

When doing oldEmails.Count , I see that I have the same amount of records in my Dictionary as were placed there in the beginning.

But when I do a check: if(oldEmails.ContainsKey(strIsoNum)) it fails., event though I have a data in my Dictionary with the given key

What am I doing wrong?

Dictionary is not serializable, and can not be saved on view state.

To save it on view state you need to convert it to a List or something other, and again re-convert it to Dictionary on page load and before you use it.

So that why when you try to save it on view state, view state actually not saves because can not serialize it. Even better use direct a List especial if you do not have too many items to search inside the list.

Some q/a on how to serialize dictionary.

Serializing .NET dictionary
Serialize Class containing Dictionary member

And one answer on How to store list of object into ViewState

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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