0

In my ASP.NET page, I want to return some data from the client-side form, which is preferable to be stored as a dictionary object. Now, I'm not very sure what type of object to use in my JavaScript function, which once accessed from the code-behind on the server (through Request.Cookies/any other suggested alternate way), can then be used as a .NET dictionary object?

Currently I'm saving the data as a specifically formatted string and then, on the server, I'm splitting it into arrays to use it. So, I'm just eager to know a better and of course, neater way to do this?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
MrClan
  • 6,402
  • 8
  • 28
  • 43
  • 4
    have you considered using JSON format? ,writing directly over the page as string and parsing it – Rafael Jan 10 '12 at 14:05
  • yes I tried, but didn't know how to convert it into a .net dictionary object, and that's where I got confused. – MrClan Jan 11 '12 at 10:32

1 Answers1

0

You can use json to transfer the data - it works great in Javascript and is supported in .Net 4.0.

First store the data in a javascript object and stringify it:

var data = {}
data.name = "Joe";
data.age = 17;

// ... whatever else you do ...

// convert to string
var jsonString = JSON.stringify(data);

// ... put in cookie, or use ajax, or use something else to give it to .Net

Then on the .Net side, you can use System.Web.Script.Serialization.JavaScriptSerializer to convert the json to a Dictionary:

String jsonString = HoweverYouGetIt();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string,object> data = serializer.DeserializeObject(jsonString) as Dictionary<string,object>;
//you can now use (int)data["name"] 

JavaScriptSerializer can be found in the System.Web.Extensions assembly which is only in .NET 4.0, but this question has other alternatives.

As for how to transmit the data - if it's a dynamic web app, use ajax. If it's a website that collects data throughout multiple pages, use cookies.

And as always, be sure to sanitize any inputs!

Community
  • 1
  • 1
zastrowm
  • 8,017
  • 3
  • 43
  • 63
  • thanks @MackieChan, **System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject()** was what I was looking for. – MrClan Jan 11 '12 at 10:34