How to store a Dictionary in a ASP.NET hidden field value?

5k views Asked by At

I am doing a web project, And I met a problem that, I want to give a counter for each date. For example, if two records are created on June 22, then the counter for June 22 should be 2. And if one record is created on June 23, then the counter for June 23 should be 1. I am thinking about using a dictionary to achieve this goal. I define a ASP.NET hidden field, and then assign a dictionary to its value in code behind. The date is the key, and the counter value is the value. The code I have so far is:

<asp:HiddenField ID="hdnRefDictionary" runat="server" />
hdnRefDictionary.Value = new Dictionary<string,int>(); // Not working since cannot convert Dictionary to string.

Thanks in advance, and Have a good day!

Cheers, Jiang Hao

3

There are 3 answers

0
Akshita On

consider using Json.Net as

Dictionary<string,string> dict=new ......//any dictionary
string json=Newtonsoft.Json.JsonConvert.SerializeObject(dict);
hdnRefDictionary.Value  = data;//you hidden field

on post/desialize simple deserialize

Dictionary<string,string> dict=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>(hdnRefDictionary.Value);

please note if you put complex objects in dictionary you may have to override their ToString() method and/or handle serialization/Deserialization yourself using JsonConvertor

0
Brian Mains On

You have to serialize it manually. You can use LINQ to do it:

string data = String.Join(";", dict.Select(i => i.Key + "=" + i.Value.ToString()));
hdnRefDictionary.Value  = data;

And then write the code to deserialize it later by splitting on ";" and building the key/value pairs based on the "=".

You can also use JSON serialization to do this. I use JSON.NET utility and it makes it really easy to serialize objects. However, JSON is a little bigger of a response output (not much, but a little) than using a querystring-like storage mechanism for what you are trying to do.

You'd want to use a hidden field if you want to manipulate the data on both the client and server; if you only need access on the server, then you'd want to use ViewState like @Imadoddin said, or some other mechanism like Cache, Session, etc. This is because it never gets output to the client (well ViewState does, but is encrypted) and is protected from anybody trying to change it.

0
Imad On

By default hidden field cannot store any thing other than string. Since Dictionary is not a string that means you have to serialize it. That's a one face on coin because you have to de-serialize it again while accessing in Dictionary object. Since it is a bit tedious work I will recommend you to use ViewState which does all the serialization and de-serialization task internally. The syntax is quite same.

ViewState["yourKey"] = AnyObject;

If still you want to use hidden field then Brian Mains' answer is perfect for you.