views:

153

answers:

3

I need to pass a javascript data to the server-side on post-back.

Ex
var jsVariableToPass = new Object();
jsVariableToPass ['key1'] = value1;
jsVariableToPass ['key2'] = value2;
jsVariableToPass ['key3'] = value3;

I'd like this to be accessible as a Hashtable on the server side. What would be the best way of doing this?

The only posts I've seen do this use a hidden input. This seems a little hacky to me and I was wondering if there was another more acceptable way of doing this. Also, if this is the only way, what would be the best way to deserialize and serialize this?

+1  A: 

Since your using AJAX, you can do this in a less Hackey method. I am not sure what ajax library your using, but YUI provides an extra parameter on their ASYNC request method

var postData = YAHOO.util.Connect.setForm(this.formValidator.form); // gets the data in the form
postData += 'var1=value1&var2=value2'; // appends your new data
YAHOO.util.Connect.asyncRequest(method, action, scope,postData); // sends the post

NOTE: Scope has to have a function called success in it to get the response.

Zoidberg
I am using Ajax in my project. However, I only want the values to be passed on postback.
helios456
+1  A: 

Here is an example of writing a JSON parser that can read directly in to a Hashtable:

http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html

You could easily just serialize the object to JSON and add it as a POST datum (either with a hidden, or using jQuery or similar).

John Gietzen
The request allows access to query variables like a hashtable currently, does this a less 'hackey' solution?
Zoidberg
How would I read and write POST datum?
helios456
+1  A: 

I guess your own comment has answered your question.

You only want the values to be passed on postback.

The only way browser and server can communicate is either via get request or post request over http protocol.

As you said you only want values to be passed on post back , then you can save the hashtable in hidden input and post or you can simulate post back using YUI as @Zoidberg has mentioned in his answer.

I do not see either using hidden input or using YUI or other JS library to simulate post back as less hacky or more hacky.

In both approach main idea is to communicate to server and those are two different ways to create a request which can be sent via browser to server.

and to answer your other question about best way to serialize and deserialize

I would recommend converting your javascript data to json string as per this example and pass that to server and using litjson to convert json data to .net objects.

N30