ListItemCollectionConverter.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Web.UI.WebControls;
  5. using System.Collections;
  6. namespace System.Web.Script.Serialization.CS
  7. {
  8. public class ListItemCollectionConverter : JavaScriptConverter
  9. {
  10. public override IEnumerable<Type> SupportedTypes
  11. {
  12. //Define the ListItemCollection as a supported type.
  13. get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(ListItemCollection) })); }
  14. }
  15. public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
  16. {
  17. ListItemCollection listType = obj as ListItemCollection;
  18. if (listType != null)
  19. {
  20. // Create the representation.
  21. Dictionary<string, object> result = new Dictionary<string, object>();
  22. ArrayList itemsList = new ArrayList();
  23. foreach (ListItem item in listType)
  24. {
  25. //Add each entry to the dictionary.
  26. Dictionary<string, object> listDict = new Dictionary<string, object>();
  27. listDict.Add("Value", item.Value);
  28. listDict.Add("Text", item.Text);
  29. itemsList.Add(listDict);
  30. }
  31. result["List"] = itemsList;
  32. return result;
  33. }
  34. return new Dictionary<string, object>();
  35. }
  36. public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
  37. {
  38. if (dictionary == null)
  39. throw new ArgumentNullException("dictionary");
  40. if (type == typeof(ListItemCollection))
  41. {
  42. // Create the instance to deserialize into.
  43. ListItemCollection list = new ListItemCollection();
  44. // Deserialize the ListItemCollection's items.
  45. ArrayList itemsList = (ArrayList)dictionary["List"];
  46. for (int i=0; i<itemsList.Count; i++)
  47. list.Add(serializer.ConvertToType<ListItem>(itemsList[i]));
  48. return list;
  49. }
  50. return null;
  51. }
  52. }
  53. }