1

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?

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
eugene.it
  • 417
  • 3
  • 13
  • 32
  • it fails ??? What is the exception/Error you get, or it just doesn't find the key ? – Habib Mar 21 '14 at 21:18
  • Have you verified that `strIsoNum` has the value you expect? Have you tried looping through the dictionary to see what values it _does_ contain? – JLRishe Mar 21 '14 at 21:19
  • I mean, it does not fail with an error, it just does not go inside of `if` condition, meaning it cannot find a key – eugene.it Mar 21 '14 at 21:39

1 Answers1

1

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

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150
  • *Dictionary is not serializable, and can not be saved on view state.* It's annotated with SerializableAttribute? http://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx – ta.speot.is Mar 21 '14 at 22:06
  • @ta.speot.is I din't know that, nether have try it - So if its add this attribute can make it work then. – Aristos Mar 21 '14 at 22:08
  • I tried to do what I did 2 days ago just right now with Visual Studio 2012. I saved my `Dictionary` into `ViewState` without converting it into `List` and then checked for the key and it worked. Even though `Dictionary` is not `serializable`. Why is that? – eugene.it Mar 23 '14 at 15:17