Search code examples
c#asp.net.netviewstate

Saving Data of type (string, List<string>) in Viewstate


What collection to use to store Key, multiple values in ViewState. My data is of type string Key, List<string> Values, i.e. a key can have one or more string values

Say I have countries and cities that I need to save in ViewState.

I will have

USA - NY, DC, Chicago

Canada - Toronto, Vancouver, Montreal

etc.

I'd like to save this data to ViewState and was wondering how best to save this without creating custom serializable objects etc. They're just strings.

Should I save them as string key, comma separated List Values?


Solution

  • It seems that this simple data could be stored in a Dictionary<string, List<string>>. The dictionary keys will be the State/Region and the values will be the cities list.

    You can initialize it like this

    Dictionary<string, List<string>> locations = new Dictionary<string, List<string>>
    {
        { "USA", new List<string> {"NY", "DC", "Chicago"}},
        { "Canada", new List<string> {"Toronto", "Vancouver", "Montreal"}},
    };
    

    Then set the ViewState entry with that data

    ViewState["locs"] = locations;