0

I have an object of a class MeetingList I want to pass this object through cookie it is giving me error while casting

Writing Cookie

HttpCookie cookies = new HttpCookie("QuickJumpCookie");
cookies["MeetingList"] = bal.GetMeetingList(personID, "Open").ToString();
Response.Cookies.Add(cookies);

Reading Cookie

HttpCookie cookies = Request.Cookies["QuickJumpCookie"];
MeetingList ml = (MeetingList) cookies["MeetingList"]; <-- Error in this line
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
Shomaail
  • 493
  • 9
  • 30
  • `ToString()` means you are storing a string - you are not storing a `MeetingList`. When reading it, you can indeed not cast that `string` to a `MeetingList`. Serializing your object (and deserializing when reading it) should do the trick.(Just making it serializable is not enough of course, if you do not actually serialize it!) – oerkelens Mar 17 '15 at 11:53
  • All HTTP is strings. So no, cookies cannot be anything else but strings. However you can parse strings to ints, bools, objects etc... Just store it as JSON string and then parse it back from JSON string to Object. – Stan Mar 17 '15 at 11:59

2 Answers2

2

I suppose you should serialize and then desirialize your MeetingList class

Serialize your object in cookie in some format(for example in JSON) and then deserialize it. Personally i use this newtonsoft.com/json library. Your code will look like

JsonConvert.SerializeObject(YourMeetingListObject) 

and then

MeetingList ml = (MeetingList) JsonConvert.DeserializeObject(cookies["MeetingList"]) 
Disappointed
  • 1,100
  • 1
  • 9
  • 21
1

What you try to do is converting a string to an instance of a class. Unfortunately you can't do that. Please follow the link: Convert String to Type in C#

You could use the JavaScriptSerializer class. More information: Turn C# object into a JSON string in .NET 4

Example:

HttpCookie cookies = new HttpCookie("QuickJumpCookie");
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(bal.GetMeetingList(personID, "Open"));
cookies["MeetingList"] = serializedResult;
Response.Cookies.Add(cookies);


HttpCookie cookies = Request.Cookies["QuickJumpCookie"];
MeetingList ml = serializer.Deserialize<MeetingList>(cookies["MeetingList"]);
Community
  • 1
  • 1
Bruniasty
  • 418
  • 5
  • 18
  • I still cud not understand the solution. I was used to using Session. in session we do thing like this. I wud be pleased if write me the code or alter my code – Shomaail Mar 17 '15 at 12:10